最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I avoid that $scope.$watch returns an undefined value? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 11

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

发布评论

评论列表(0)

  1. 暂无评论