【问题标题】:Angularjs ng-repeat array - duplicate valuesAngularjs ng-repeat 数组 - 重复值
【发布时间】:2015-04-23 14:20:44
【问题描述】:

所以我只是从 Angular JS 开始,在处理数组时对 ng-repeat 有点困惑。下面的代码不能按原样工作......但是当我将 dayNames 更改为一个对象并为其提供键值对时,它很好。

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

myApp.controller("dayCtrl",function($scope){
	$scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
	<script src="angular.js"></script>
	<script src="controller.js"></script>	
</head>
<body ng-controller="dayCtrl">
	<h2>Hello, these are the days of the week</h2>
	<ul>
		<li ng-repeat="day in dayNames">{{day}}</li>
	</ul>
</body>
	

</html>

【问题讨论】:

    标签: arrays angularjs ng-repeat


    【解决方案1】:

    它不能按原样工作,因为数组中有重复项。当您重复基元数组时,angular 用于将数组中的项目与 DOM 元素相关联的默认唯一键是数组本身中的项目。当然,在您的情况下,它不是唯一的,并且会导致中继器错误重复。

    您也可以使用track by $index 来避免这种情况,这会使索引成为标识符。

    ng-repeat="day in dayNames track by $index"
    

    当您使用对象数组(没有跟踪依据)时,角度会将唯一 id 添加到数组中每个项目上名为 $$hashkey 的新属性中。然后,此属性用作将 DOM 元素与数组中的相应项通过标识关联的键。在数组中移动相同的对象将以相同的方式在 DOM 中移动 DOM 元素。因此,当您使用对象数组时,您不会看到任何问题,因为所有这些哈希键都是唯一的。

    var myApp = angular.module('exampleApp', []);
    
    myApp.controller("dayCtrl",function($scope){
    	$scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <!DOCTYPE html>
    <html ng-app="exampleApp">
    <head>
    	<script src="angular.js"></script>
    	<script src="controller.js"></script>	
    </head>
    <body ng-controller="dayCtrl">
    	<h2>Hello, these are the days of the week</h2>
    	<ul>
    		<li ng-repeat="day in dayNames track by $index">{{day}}</li>
    	</ul>
    </body>
    	
    
    </html>

    【讨论】:

    • 当我在上面的代码中删除数组中的重复天数时,由于某种原因它仍然无法正常工作。
    • @John23 好吧,您需要添加 Angular 才能使 Angular 应用程序正常工作。 :) 看看控制台。
    • @John23 现在检查您问题中的 sn-p。
    • 在将其从对象切换回数组后出现局部变量名称错误....通过脚本元素连接到角度。完美运行...感谢您的帮助。
    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多