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.
Is it possible to rewrite my code to avoid the unnecessary check for undefined
?
Here is a minimal example:
1) jsfiddle
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:
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';
}
});
});
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
controller('myCtrl', function($scope) { var a = //something in the scope //put it in the root scope }); angular. module('myApp'). controller('myCtrl2', function($scope) { var b = //get var a from root scope somehow //use var b });
Each AngularJS application has exactly one root scope, but may have any number of child scopes.
If you set a default empty value for your watched property in your view model you won't have the problem with undefined
values.
In your case add this before or after $scope.textLength
initialization (check this fiddle).
$scope.text = '';
Another option to avoid the undefined error is you can wrap your function in a hasOwnProperty if statement.
$scope.$watch('text', function (value) {
if($scope.hasOwnProperty('text')) {
if (typeof value !== 'undefined') {
$scope.textLength = value.length;
} else {
$scope.textLength = 'observed value is undefined';
}
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With