2014-10-10 66 views
1

Angular還很新,所以請耐心等待。我有一個使用ng-repeat生成的單選按鈕列表。我將選定的對象存儲在同一控制器上的單獨變量中。AngularJS通過不選擇初始值的ng-repeat軌跡

所選對象正在使用列表中某個對象的不同實例進行設置。我認爲由於ID是相同的,使用「track by」表達式將在列表中選擇正確的項目,但事實並非如此。 如果我選擇一個單選按鈕,它將按預期更新所選變量。

我做錯了什麼?這是不好的模式?

<form name="myForm" ng-controller="MyCtrl"> 
    <label ng-repeat="person in people track by person.id"> 
     <input type="radio" ng-model="$parent.selected" ng-value="person" /> 
     {{person.name}} 
    </label> 
</form> 

這裏是我的控制器:

angular.module('ngAppDemo', []).controller('MyCtrl', MyCtrl) 

function MyCtrl($scope) { 
    $scope.selected = { id: 2, name: "Paul" }; 
    $scope.people = [ 
     { id: 1, name: "John" }, 
     { id: 2, name: "Paul" }, 
     { id: 3, name: "George" }, 
     { id: 4, name: "Frank" } 
    ]; 
} 

這裏是我的Plunker

更新:
我承認這樣一個事實,如果我使用一個對象來自同一個集合,它會奏效。但是,這不是我目前設置的方式。我用於「選定」的實例來自不同的函數,因此不是來自給定的列表。

+2

http://plnkr.co/edit/2bN7ImuFx8yBbBjZcHm2?p=preview - 如果您從服務器獲取新數據,「track by」用於不重新創建DOM元素 – gearsdigital 2014-10-10 18:59:50

+1

http://www.codelord.net/2014/04/15/improve-ng-repeat-performance-with-track-by/ – gearsdigital 2014-10-10 19:05:59

回答

3

什麼,現在是固定的:

http://plnkr.co/edit/LWXe4dFzfdqTOZXmatpQ?p=preview

你只需要確保選中指向列表中的某些東西。它不會按參考值進行比較。

function MyCtrl($scope) { 
$scope.people = [ 
    { id: 1, name: "John" }, 
    { id: 2, name: "Paul" }, 
    { id: 3, name: "George" }, 
    { id: 4, name: "Frank" } 
]; 
$scope.selected = $scope.people[1]; 
} 

更新 所有你需要做的就是簡單地寫匹配常規自己匹配ID不管是真實生產它的其他功能是自己的對象,並找到在$ scope.people列表相同的對象。例如:

function findSelectedPerson(selected) { 
    for(var i = 0; i < $scope.people.length; i++) { 
     if($scope.people[i].id == selected.id) return $scope.people[i]; 
    } 
    return null; 
} 

這會解決它。

+0

謝謝你的迴應。看我的更新。我想我需要找出一個方法來解決這個問題。 – Airn5475 2014-10-10 19:52:11

+0

感謝您的更新,幾乎是我最終做的......有一種方法可以自動執行此操作。 – Airn5475 2014-10-13 12:45:10

+0

很好,你能將這個標記爲答案嗎? – chubbsondubs 2014-10-13 20:27:53

1

提示

$scope.selected = { id: 2, name: "Paul" }; 
$scope.people = [ 
    { id: 1, name: "John" }, 
    { id: 2, name: "Paul" }, 
    { id: 3, name: "George" }, 
    { id: 4, name: "Frank" } 
]; 

console.log($scope.selected == $scope.people[1]) // false 

$ scope.selected劑量不匹配$ scope.people

+0

感謝您的回覆。沒有必要提示,我明白這兩個對象是不相等的。 :(我試圖用價值來尋找一場比賽 – Airn5475 2014-10-10 19:50:02