带有轨道的重复ng-repeat

时间:2017-09-19 06:18:43

标签: html angularjs angularjs-track-by

如何允许使用track by重复ng-repeat并从控制器更新ng-repeat列表?

通过$ index使用track我无法更新范围变量,但我想在ng-repeat中允许重复对象

条件: 1)允许重复ng-repeat 2)使用track by 3)从控制器更新ng-repeat列表

HTML

<div>
    <ng-repeat="question in pagedata.questions track by $index"> 
            <p>{{question.questionText}}<p>
        <div ng-repeat="option in question.optionList track by $index">
                <p ng-click="changeNextQuestion(question.nextQuestionId)">{{option}}</p>
        </div>

</div>

控制器

  $scope.pagedata.questions = [
     {
        "questionId" : 1
        "questionText" : "A"
        "optionList" : [A1, A2, A3],
        "nextQuestionId"  : 2

     },
     {
        "questionId" : 2
        "questionText" : "B"
        "optionList" : [B1, B2, B3],
        "nextQuestionId"  : 2
     },
 {
        "questionId" : 3
        "questionText" : "C"
        "optionList" : [C1, C2, C3],
        "nextQuestionId"  : 2
     }
    ];
$scope.pagedata.questionsBack = angular.copy($scope.pagedata.questions);

$scope.changeNextQuestion = function(nextQuestionId){
    var nextQuestion = findNextQuestionIndex($scope.pagedata.questions, nextQuestionId);
    $scope.pagedata.questions[0] = $scope.pagedata.questionsBack[nextQuestion];
    });
//I want to update view with new value.
}


}

2 个答案:

答案 0 :(得分:0)

按$ index&#39;添加&#39;到ng-repeat。

更多信息,请参阅此链接https://docs.angularjs.org/error/ngRepeat/dupes

答案 1 :(得分:0)

你检查一下one. 我希望这个对你有帮助。

在控制器中

var studentsList = [
    {"Id": "101", "name": "siva"},
    {"Id": "101", "name": "siva"},
    {"Id": "102", "name": "hari"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "104", "name": "ramesh"},
];

 var uniqueStandards = UniqueArraybyId(studentsList ,"id");

 function UniqueArraybyId(collection, keyname) {
  var output = [], 
  keys = [];

  angular.forEach(collection, function(item) {
    var key = item[keyname];
    if(keys.indexOf(key) === -1) {
      keys.push(key);
      output.push(item);
    }
  });
  return output;
};