[英]Can I avoid that $scope.$watch returns an undefined value?
When I observe a scope variable in Angular via $scope.$watch
, it seems to be undefined
only at the first call of the watch function. 当我通过
$scope.$watch
观察Angular中的范围变量时,它似乎仅在watch函数的第一次调用时undefined
。
Is it possible to rewrite my code to avoid the unnecessary check for undefined
? 是否可以重写我的代码以避免对
undefined
进行不必要的检查?
Here is a minimal example: 这是一个最小的例子:
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';
}
});
});
If you set a default empty value for your watched property in your view model you won't have the problem with undefined
values. 如果在视图模型中为监视属性设置默认空值,则不会出现
undefined
值的问题。
In your case add this before or after $scope.textLength
initialization (check this fiddle ). 在你的情况下,在
$scope.textLength
初始化之前或之后添加它(检查这个小提琴 )。
$scope.text = '';
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'; } }); } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.