问题
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
- Does ng-init watch over change on instantiated property like ng-model does?
- How do I watch the changes in the property instantiated by ng-init?
- 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