2014-09-29 49 views
2

我對codepen此代碼示例:。http://codepen.io/anon/pen/hauvbAngularJS:'不允許在中繼器中複製。使用「軌道由」表達式指定唯一鍵「

的問題是,NG-重複後,我把我的表單對象放入數組不更新,我可以看到內容被添加到數組中,但ng-repeat沒有更新。我嘗試使用$ apply,但是我被告知我不需要這樣做,因爲ng-click會爲我更新$摘要。明白我錯過了什麼感謝

var app = angular.module('theTasker', []); 


app.controller('MyTasks', [function(){ 
    this.tasks = [ 
    { 
     title: "This is the title", 
     completed: false 
    }, 
    { 
     title: "This is the title", 
     completed: true 
    }, 
    { 
     title: "This is the title", 
     completed: false 
    } 
    ]; 

    this.myform = { 
    item: "Item Title", 
    completed: false 
    }; 
    this.addtask = function(){ 
    this.tasks.push(this.myform); 
    }; 
}]) 

編輯:。

上面的代碼會產生此錯誤:

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

回答

4

在測試你的代碼中,我得到了一個錯誤

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

改變你的HTML NG-重複線,看起來像這樣:

li(ng-repeat="task in mytasks.tasks track by $index") 

這裏是一個例子plnkr

你也有一個在myform對象中的拼寫錯誤,指定'物品'而不是'標題',所以新的任務增加了,但標題沒有顯示。

更改它看起來是這樣的:在這裏

this.myform = { 
    title: "Item Title", 
    completed: false 
}; 

是一個固定code-pen

+0

謝謝 - 這是問題所在。我希望你不介意我延長這個問題,現在它正在工作我注意到,因爲我添加了兩個或三個他們現在都更新的各個項目,現在它們的值都是最新的項目。基本上我只是複製對象而不是創建對象的新實例。我不確定在這種情況下在哪裏實現某種「新」構造函數。我會在哪裏做? – motleydev 2014-09-29 15:51:40

+0

您需要使用輸入中的值準備一個對象,並將其按下按鈕單擊。就像現在一樣,只有真實的數據。 – 2014-09-30 07:12:57

0

您的數組需要位於作用域上。 Trythis確保NG-重複是重複了 「任務」:

app.controller('MyTasks', ['$scope', function($scope){ 
    $scope.tasks = [ 
    { 
     title: "This is the title", 
     completed: false 
    }, 
    { 
     title: "This is the title", 
     completed: true 
    }, 
    { 
     title: "This is the title", 
     completed: false 
    } 
    ]; 

    this.myform = { 
    item: "Item Title", 
    completed: false 
    }; 
    this.addtask = function(){ 
    $scope.tasks.push(this.myform); 
    }; 
}]) 
+0

它通過作用範圍控制器「控制器」語法像codepen例子。它不能以這種方式工作嗎?初始ng-repeat看起來很好,數組更新正常,只是ng-repeat不更新。 – motleydev 2014-09-29 10:58:16

+0

爲了響應更改而監視的值需要位於範圍內。我認爲你所做的是給控制器對象一些額外的屬性,ng-repeat無法「觀察」更改。 – Fordio 2014-09-29 11:07:58

相關問題