我正在使用角度js在杂货店列表上工作。我试图使用id生成器将一个项目添加到列表中我在输入字段中输入时能够添加第一个项目,但我无法添加另一个随机输入的项目。
我使用underscore.js作为外部库。
我收到这样的错误: 错误:ngRepeat:dupes 转发器中的重复键
var app = angular.module('groceryapp',["ngRoute"])
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: "view1.html",
controller: "groceryctl"
})
.when('/additem',{
templateUrl: "view2.html"
})
.when('/additem/:id',{
templateUrl: "view2.html"
})
.otherwise({
redirectTo: '/'
})
})
app.factory("Groceryservice", function(){
var groceryservice = [];
groceryservice.items = [
{id:1,completed:true,itemName:"Bread",dateMf:"03-05-2017"},
{id:2,completed:true,itemName:"Unclechips",dateMf:"07-05-2017"},
{id:3,completed:true,itemName:"So-sugarcandy",dateMf:"13-09-2014"},
{id:4,completed:true,itemName:"Frestos",dateMf:"23-06-2015"},
{id:5,completed:true,itemName:"Mr.john flour",dateMf:"17-04-2017"},
{id:6,completed:true,itemName:"Gems",dateMf:"19-07-2015"},
{id:7,completed:true,itemName:"Agrade-apples",dateMf:"15-08-2016"},
{id:8,completed:true,itemName:"Pepsi",dateMf:"21-09-2017"},
{id:9,completed:true,itemName:"Peanut-jam",dateMf:"19-11-2016"},
{id:10,completed:true,itemName:"Mushrooms",dateMf:"06-11-2017"}
];
groceryservice.getNewId = function() {
if(groceryservice.newId) {
groceryservice.newId++;
return groceryservice.newId;
}
else{
var maxId = _.max(groceryservice.items, function(entry){return entry.id;})
groceryservice.newId = maxId.id + 1 ;
return groceryservice.newId;
}
};
groceryservice.save = function(entry){
entry.id = groceryservice.getNewId();
groceryservice.items.push(entry);
}
return groceryservice;
})
app.controller('groceryctl', ["$scope","$routeParams","$location","Groceryservice",function($scope,$routeParams,$location,Groceryservice){
$scope.title="Gstore";
$scope.items=Groceryservice.items;
$scope.additem = { id:11,completed:true,itemName:"",dateMf:new Date() };
$scope.save = function(){
Groceryservice.save($scope.additem);
$location = ('/');
}
console.log($scope.items);
}])
app.controller('titlectl', ["$scope","Groceryservice",function($scope,Groceryservice){
$scope.title=Groceryservice.items[0].itemName;
}]);
<div class="col-sm-offset-2 col-sm-8">
<ul class="list-group">
<li class="list-group-item text-center clearfix" ng-repeat="item in items | orderBy:'-dateMf' ">
<span class="" style="font-size:18px;font-weight:bold;">{{item.itemName | uppercase}}</span>
</li>
</ul>
</div>
答案 0 :(得分:1)
当ng-repeat遇到数组中的重复项时,通常会发生欺骗错误,以通过$ index来绕过此添加轨道:
<li class="list-group-item text-center clearfix" ng-repeat="item in items track by $index | orderBy:'-dateMf' ">