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

空扰寡人 提交于 2019-12-30 08:52:31

问题


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:


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



来源:https://stackoverflow.com/questions/25574048/does-ng-init-watch-over-change-on-instantiated-property-like-ng-model-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!