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

查看:130
本文介绍了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?

您可以像观看其他财产一样观看,但是观看并不意味着观看会被触发.监视仅在摘要周期内触发,并且摘要周期仅在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事件,然后将输入的值分配给属性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

plnkr

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

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