即使绑定到更深的对象或数组,也使ngModel触发$ render

时间:2013-06-30 14:31:03

标签: javascript angularjs angularjs-directive angularjs-scope

绑定到ngModel时,如果有对象:

scope.someObj = { 
    prop: 10, 
    prop2: [20, 30], 
    subObj: {
        prop: 40
    } 
}

并将其附加到某些输入字段,如下所示:

<input type="number" ng-model="someObj.prop" />
<input type="number" ng-model="someObj.prop2[0]" />
<input type="number" ng-model="someObj.prop2[1]" />
<input type="number" ng-model="someObj.subObj.prop" />

并将事件监听器放入每个的$ render触发器中,如下所示:

ngModel.$render = function() {console.log("Hello");};

$ render只会触发第一个输入被编辑,但绝不会在其他输入被编辑时。基本上,$ render不会触发绑定到深度超过一个级别的模型。

有没有办法强迫它这样做?

2 个答案:

答案 0 :(得分:2)

我使用了$ scope。$ watch来监控它。

<input ng-model="myInputs.a">
<input ng-model="myInputs.b">

var obj = {};

$scope.$watch('myInputs', function(){
   // do whatever here ....
   // you can assign variables to myInputs
   obj.x = myInputs.a;

   }, true);

此处的关键是添加最后一个参数true,因此它会深度监控您的对象。

答案 1 :(得分:0)

您的解决方案是like this

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" data-semver="1.0.7"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <input type="number" ng-model="someObj.prop" />
    <input type="number" ng-model="someObj.prop2[0]" />
    <input type="number" ng-model="someObj.prop2[1]" />
    <input type="number" ng-model="someObj.subObj.prop" />
  </body>

</html>