Angular $ watch:TypeError:无法读取undefined的属性

flo*_*urr 3 angularjs

我有这个$watch过滤器应用于日期格式:

$scope.$watch(function() {
    return pn.myObj.birthDate;
},function(n,o){
    var dateView = $filter('date')(pn.myObj.birthDate,'yyyy-MM-dd');
    pn.myObj.birthDate = dateView;
});
Run Code Online (Sandbox Code Playgroud)

我第一次加载我在控制台中读取的页面:

TypeError:无法读取undefined的属性'birthDate'

如何防止在$watch我的对象出现时出现的问题undefined

mof*_*jed 7

调用$ watch函数时,您的对象未初始化.在尝试访问其中一个属性之前检查它是否存在.

$scope.$watch(function() {
    return pn && pn.myObj && pn.myObj.birthDate;
}
Run Code Online (Sandbox Code Playgroud)