gpt4 book ai didi

angularjs - 在 ngRepeat 中自动包含 $$hashKey

转载 作者:行者123 更新时间:2023-12-03 08:02:13 25 4
gpt4 key购买 nike

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

在我的代码中,我通过 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 文件中出现错误:

Uncaught TypeError: Cannot read property 'nodeName' of undefined

我都试过了

  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 这个来获得数组

最佳答案

如果 ng-repeat 中没有设置 track by,AngularJS 会向你的对象添加一个 $$hashKey 属性来跟踪你的更改指示。只需尝试使用 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);
}


});

> demo fiddle

关于angularjs - 在 ngRepeat 中自动包含 $$hashKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com