Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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';
      }
    });
});
like image 464
Philipp Claßen Avatar asked Mar 18 '14 13:03

Philipp Claßen


People also ask

What causes undefined JavaScript?

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 .

Is undefined and null false?

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.

How to declare rootScope variable in AngularJS?

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 });

What is the number of scopes allowed in an AngularJS application?

Each AngularJS application has exactly one root scope, but may have any number of child scopes.


2 Answers

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 = '';
like image 69
RaYell Avatar answered Oct 22 '22 16:10

RaYell


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';
      }
    });
  }
};
like image 22
ng-darren Avatar answered Oct 22 '22 15:10

ng-darren