在ngRepeat中自动包含$$ hashKey

时间:2018-03-17 11:43:21

标签: angularjs

我已经找到了一个解决方案,我已经尝试了所有但我没有找到解决方案。

在我的代码中,我通过ajax从数据库中获取一个数组。

我正在获得正确的数组,如下所示:

[{"id":"1","name":"product 1","image":null},{"id":"2","name":"product 2","image":null},{"id":"3","name":"product 3","image":null}];

但是当我在ng-repeat中使用它时,它会添加$$hashKey。因此,我在vendor.js文件中收到错误:

  

未捕获的TypeError:无法读取未定义的属性“nodeName”

我已经尝试了所有

  angular.copy($scope.myArray);
  angular.toJson($scope.myArray);
  JSON.stringify($scope.myArray);

我也尝试过:

  <div ng-repeat="smallArray in myArray track by $id($index)">

此方法删除$$hashKey,但它以字符串形式返回。

例如:

       $scope.ans = angular.toJson($scope.myArray);

等于

 $scope.ans = '[{"id":"1","name":"product 1","image":null},{"id":"2","name":"product 2","image":null},{"id":"3","name":"product 3","image":null}]';

这是我的HTML

    <div class="slide-wrap" ng-repeat="smallArray in myArray">
        <div class="slide__content-wrap">
          <h1 class="title">{{smallArray.name}}</h1>
    </div>
    <div class="slide__content-wrap__inside show-for-large-up">
       <p class="description">{{smallArray.image}}</p>
         <a class="btn btn--transparent--red" href="/premium-ice-cream">view 
             all flavors</a>
    </div>
    </div>

任何人都可以推荐我如何删除$$hashKey

来获取数组

1 个答案:

答案 0 :(得分:3)

如果$$hashKey指令中未设置track by,AngularJS会为您的对象添加ng-repeat属性,以跟踪您的更改。只需尝试使用ng-repeat="item in data track by item.id"即可。通过这种方式,AngularJS将此“唯一”值用于其内部跟踪。

视图

<div ng-controller="MyCtrl">
   <div ng-repeat="item in data track by item.id">
       {{ item | json }}
   </div>
   <br />
   <div ng-repeat="item in hashData">
       {{ item | json }}
   </div>
   <br />
   <br />
   <button ng-click="track()">
    Click me to log
   </button>
</div>

AngularJS应用程序

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  $scope.data = [{
    "id": "1",
    "name": "product 1",
    "image": null
  }, {
    "id": "2",
    "name": "product 2",
    "image": null
  }, {
    "id": "3",
    "name": "product 3",
    "image": null
  }];


  $scope.hashData = [{
    "id": "1",
    "name": "product 1",
    "image": null
  }, {
    "id": "2",
    "name": "product 2",
    "image": null
  }, {
    "id": "3",
    "name": "product 3",
    "image": null
  }];


  $scope.track = function () {
    console.log($scope.data);
    console.log($scope.hashData);
  }


});

<强>&GT; demo fiddle