ng-init 是否像 ng-model 一样监视实例化属性的变化? [英] Does ng-init watch over change on instantiated property like ng-model does?

查看:18
本文介绍了ng-init 是否像 ng-model 一样监视实例化属性的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ng-init 是否像 ng-model 一样监视实例化属性的变化?

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}}

这里是 plnkr

  1. ng-init 是否像 ng-model 一样监视实例化属性的变化?
  2. 如何观察 ng-init 实例化的属性的变化?
  3. 上面的 $watch 函数有什么问题?

推荐答案

ng-init 是否像 ng-model 一样监视实例化属性的变化?

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.

如何观察 ng-init 实例化的属性的变化?

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

您可以像观看任何其他属性一样观看,但观看它并不意味着手表会被触发.Watches 仅在摘要循环期间触发,并且仅当 angular 与特定操作有关时才会调用摘要循环.

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.

上面的 $watch 函数有什么问题?

What's wrong with the $watch function above?

你在 prop1 上的监视永远不会被执行(在 ng Init 初始化之后),因为你永远不会改变模型值,因为没有 ngModel 绑定到它.并且没有对元素进行角度动作,因此不会发生消化循环.

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.

举个例子,只是在元素上附加一个keyup事件,并将input的值赋给属性myProp,因为你已经注册了keyup处理程序,它会在处理程序运行后触发摘要循环,你会看到手表被执行并且绑定被更新

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

这篇关于ng-init 是否像 ng-model 一样监视实例化属性的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆