【问题标题】:Duplicate ng-repeat with track by [duplicate]重复 ng-repeat 并通过 [重复] 跟踪
【发布时间】:2017-09-19 06:18:43
【问题描述】:

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

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

条件: 1) 允许在 ng-repeat 中重复 2)使用跟踪 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.
}


}

【问题讨论】:

  • 使用 $index 的轨道。更新只是更新范围值。

标签: html angularjs angularjs-track-by


【解决方案1】:

将“track by $index”添加到 ng-repeat。

更多信息请查看此链接https://docs.angularjs.org/error/ngRepeat/dupes

【讨论】:

    【解决方案2】:

    你检查这个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;
    };
    

    【讨论】:

    • ng-repeat="object in objects track by $index" when ng-click = "pushDuplicateAndUpdateView()" -> 我想将重复的对象推送到列表并更新视图控制器 { $scope.Objects [A,B,C,B];函数 pushDuplicateAndUpdateView(){ $scope.Objects[0] = C; } }
    • 现在你可以检查了,我更新了我的答案。
    • 请给出上述意见的解决方案
    • 好的,您可以更新您的问题吗?另外,把你的代码放在这里。
    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多