Does ng-init check for a change to an instance property like ng-model?

Does ng-init check for a change to an instance property like ng-model?

Apparently not, so I set the clock 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 check for a change to an instance property like ng-model?
  • How to see changes in properties created using ng-init?
  • What is wrong with the $ watch function above?
+5
source share
1 answer

Does ng-init check for a change to an instance property like ng-model?

No, this is only for initializing a property in a scope. I would recommend not using it. The markup is not for an initialization variable, you should do this in your controller as much as possible.

How to see changes in properties created using ng-init?

You can watch in the same way as you look at any other property, but viewing it does not mean that the clock works. The clock only fires during the digest cycle, and the digest cycle is only called if angular has something to do with a particular action.

What happened to the $ watch function above?

Your clock on prop1 will never be executed (after the initialization of ng Init), because you never change the value of the model, since there is no binding to it with ngModel. And the angular action on the element is not performed, and therefore, the digest cycle will not happen.

As an example, simply attach the keyup event to the element and assign an input value to the myProp property, since you registered the keyboard handler, it will call a digest cycle after the handler starts, and you will see the clock and the binding are updated

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

plnkr

+8
source

Source: https://habr.com/ru/post/1201438/


All Articles