我可以避免使用$ scope.$ watch返回一个未定义的值吗?

Phi*_*ßen 5 javascript angularjs

当我在Angular via中观察范围变量时$scope.$watch,它似乎undefined只是在watch函数的第一次调用时.

是否可以重写我的代码以避免不必要的检查undefined

这是一个最小的例子:

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>
Run Code Online (Sandbox Code Playgroud)

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';
      }
    });
});
Run Code Online (Sandbox Code Playgroud)

RaY*_*ell 11

如果在视图模型中为监视属性设置默认空值,则不会出现undefined值问题.

在你的情况下,在$scope.textLength初始化之前或之后添加它(检查这个小提琴).

$scope.text = '';
Run Code Online (Sandbox Code Playgroud)