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
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.
Ng-init directive is used to initialize a variable, which will allows evaluating an expression in given scope.
In Angular 1. x, ngInit is called when template is re-rendered. In other words “ng-init” is called, when I take turns back to a page. In Angular2, there is no “ng-init” but we can create a ways like this using the directive and ngOnInit class.
The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With