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';
}
});
});
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';
}
});
});
Share
Improve this question
edited Oct 24, 2018 at 7:04
Prashant Pokhriyal
3,8274 gold badges31 silver badges41 bronze badges
asked Mar 18, 2014 at 13:12
Philipp ClaßenPhilipp Claßen
44k36 gold badges160 silver badges251 bronze badges
2
- 2 You can initialize text. – Mike Cheel Commented Mar 18, 2014 at 13:14
- jsfiddle/T7LTv/7 – Vladimir Commented Jun 3, 2017 at 19:00
2 Answers
Reset to default 11If 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';
}
});
}
};