【问题标题】:Update array items in ng-repeat table in AngularJS在 AngularJS 中更新 ng-repeat 表中的数组项
【发布时间】:2018-09-21 19:21:46
【问题描述】:

我有一个从 JSON 文件中提取数据的 AngularJS 应用程序。使用详细信息模板中的 ng-repeat 将部分数据添加到表中。当我选择第一个对象时,假设进入表格的数据工作正常。但是,当我单击另一个对象时,前一个对象的数据值会保留下来,而新选择的对象的数据值会添加到下方。

如何让表中的值仅在选择其对象时显示?我正在使用.push() 方法插入值,所以我认为if statement 中的.slice() 可能是一个解决方案,但到目前为止还没有运气。

JS

pplApp.directive("peopleDetails", function(FindSearch) {
return {
restrict: 'E',
scope: {
  people: "=ngPeople"
},
templateUrl: 'ppl_details.html',
controller: function($scope, $element, $attrs, $templateCache, $rootScope, FindSearch) {
  $scope.likesAndDislikes = [];
  var results = [];
  var item;
  $scope.getNumber = function() {
    array = new Array($scope.people.rating)
    return array;
  }

  $scope.getLikesAndDislikes = function() {
    $scope.likeAndDislikes = [];
    results = [];

    $scope.people.Likes.forEach(function(value, key) {
      var insert = {
        'likes': value,
        'dislikes': $scope.people.Dislikes[key]
      };
      $scope.likesAndDislikes.push(insert);
    });
  }

  $scope.$watch('people', function() {
    $scope.getLikesAndDislikes();
  });
}
};
});

这是我在Plunker 中的代码以获取完整信息。

【问题讨论】:

    标签: angularjs json


    【解决方案1】:

    这是因为您没有重置相同的 likesAndDislikes 数组模型变量。从 peopleDetails 指令将您的方法更新为:

    $scope.getLikesAndDislikes = function() {
        $scope.likesAndDislikes = [];
        results = [];
    
        $scope.people.Likes.forEach(function(value, key) {
          var insert = {
            'likes': value,
            'dislikes': $scope.people.Dislikes[key]
          };
          $scope.likesAndDislikes.push(insert);
        });
    }
    

    这里我唯一更新的是重置数组变量名:$scope.likesAndDislikes = []; 你拼错和使用的是 likeAndDislikes 。

    更新plunker Example

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多