Does ng-init watch over change on instantiated pro

2019-02-17 15:32发布

Does ng-init watch over change on instantiated property like ng-model does?

Apparently not, so I set a watch as shown below:

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.$watch('myProp1', function(newVal, oldVal){
    $scope.myProp1 = newVal
  })
});

html

<body ng-controller="MainCtrl">
<input ng-init='myProp="my property"'>{{myProp}}</br>
<input ng-init='myProp1="my 1 property"'>{{myProp1}}</br>
<input ng-init='myProp11="my 11 property"' ng-model='myProp11'>{{myProp11}}

Here is plnkr

  1. Does ng-init watch over change on instantiated property like ng-model does?
  2. How do I watch the changes in the property instantiated by ng-init?
  3. What's wrong with the $watch function above?

1条回答
何必那么认真
2楼-- · 2019-02-17 16:02

Does ng-init watch over change on instantiated property like ng-model does?

No, It is only to initialize a property on the scope. I would recommend not to use it. Markup is not for variable initialization, you should do it in your controller as much as possible.

How do I watch the changes in the property instantiated by ng-init?

You can watch just like watching any other property, but watching it does not mean that watch will get triggered. Watches are triggered only during the digest cycle and digest cycle gets invoked only if angular has something to do with a particular action.

What's wrong with the $watch function above?

Your watch on prop1 will never get executed (after ng Init initialization), because you are never changing the model value since there is no ngModel bound to it. And there is no angular action is done on the element and hence digest cycle will not happen.

As an example just attach a keyup event on the element, and assign the value of input to the property myProp, because you have registered keyup handler it will trigger digest cycle after the handler is run, and you will see the the watch getting executed and binding getting updated

 <input ng-init='myProp="my property"' ng-keyup="test(myProp=$event.target.value)">{{myProp}}

plnkr

查看更多
登录 后发表回答