我有使用ngRepeater显示的数组,但是使用这个指令,我使用ngInit指令执行函数,该函数应该返回要显示的对象。一切正常工作,但是当我添加“新”按钮时,我将新值添加到数组,然后功能“SetPreview”只有在我认为应该根据数组值的数量执行功能时才执行。我怎样才能做到这一点?
用户界面:
- <body ng-app>
- <ul ng-controller="PhoneListCtrl">
- <button ng-click="add()">Add</button>
- <li ng-repeat="phone in phones" ng-init="displayedQuestion=SetPreview(phone);">
- {{displayedQuestion.name}}
- <p>{{displayedQuestion.snippet}}</p>
- </li>
- </ul>
- </body>
控制器:
- function PhoneListCtrl($scope) {
- $scope.phones = [
- {"name": "Nexus S","snippet": "Fast just got faster with Nexus S."},{"name": "Motorola XOOM™ with Wi-Fi","snippet": "The Next,Next Generation tablet."},{"name": "MOTOROLA XOOM™",Next Generation tablet."}
- ];
- $scope.add = function(){
- this.phones.push({name:'1',snippet:'n'});
- };
- $scope.SetPreview = function(phone)
- {
- //here logic which can take object from diffrent location
- console.log(phone);
- return phone;
- };
- }
编辑:
Here is more complicated sample: – >现在收集的手机是空的,当你点击添加按钮新项目被添加并被设置为可编辑(您可以更改文本字段中的值),当ngRender执行时SetPreview函数返回可编辑对象(它的工作像预览)。现在尝试再次单击添加按钮,您可以看到第一个项目的可编辑值仍然呈现给用户,但是我想刷新整个ng-repeater。
你正在进行一个角色表演功能。
基本角度可以看到数组中的元素(例如’A’)是相同的对象引用,所以它不会再次调用ng-init。这是有效的。即使您将一个旧列表连接到一个新的列表中,Angular也会看到它是相同的引用。
如果相反,您创建一个与旧对象具有相同值的新对象,则它具有不同的引用,并且Angular重新引用它:
错误的例子,你所寻找的:http://jsfiddle.net/fqnKt/37/
- $scope.add = function(item) {
- var newItems = [];
- angular.forEach($scope.items,function(obj){
- this.push({val:obj.val});
- },newItems)
- newItems.push({val:item})
- $scope.items = newItems;
- };