通过不选择初始值来进行AngularJS ng-repeat轨道

时间:2014-10-10 18:49:18

标签: javascript angularjs angularjs-ng-repeat

Angular还是比较新的,所以请耐心等待。我有一个单选按钮列表,我使用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 个答案:

答案 0 :(得分: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;
}

那就解决了。

答案 1 :(得分: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

中的任何内容都不匹配