javascript 我可以避免 $scope.$watch 返回未定义的值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22480448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I avoid that $scope.$watch returns an undefined value?
提问by Philipp Cla?en
When I observe a scope variable in Angular via $scope.$watch, it seems to be undefinedonly at the first call of the watch function.
当我通过 观察 Angular 中的作用域变量时$scope.$watch,它似乎undefined只在第一次调用 watch 函数时发生。
Is it possible to rewrite my code to avoid the unnecessary check for undefined?
是否可以重写我的代码以避免不必要的检查undefined?
Here is a minimal example:
这是一个最小的例子:
1) jsfiddle
1)jsfiddle
2) HTML:
2)HTML:
<div ng-app="MyApp">
<div ng-controller="MyCtrl">Enter some text:
<input type="text" ng-model="text" size="30" />
<p>You entered: {{text}}</p>
<p>Length: {{textLength}}</p>
</div>
</div>
3) Javascript:
3)Javascript:
angular.module('MyApp', []).controller(
'MyCtrl', function ($scope) {
$scope.textLength = 0;
$scope.$watch('text', function (value) {
if (typeof value !== 'undefined') {
$scope.textLength = value.length;
} else {
$scope.textLength = 'observed value is undefined';
}
});
});
回答by RaYell
If you set a default empty value for your watched property in your view model you won't have the problem with undefinedvalues.
如果你在你的视图模型中为你的 watch 属性设置了一个默认的空值,你就不会有undefined值的问题。
In your case add this before or after $scope.textLengthinitialization (check this fiddle).
在你的情况下,在$scope.textLength初始化之前或之后添加它(检查这个小提琴)。
$scope.text = '';
回答by ng-darren
Another option to avoid the undefined error is you can wrap your function in a hasOwnProperty if statement.
避免未定义错误的另一个选择是您可以将函数包装在 hasOwnProperty if 语句中。
$scope.$watch('text', function (value) {
if($scope.hasOwnProperty('text')) {
if (typeof value !== 'undefined') {
$scope.textLength = value.length;
} else {
$scope.textLength = 'observed value is undefined';
}
});
}
};

