contactManager.controller('contactsList',
function contactsList($scope){
$scope.myId = 0;
$scope.contacts = [{id:$scope.myId,name:'Default',mail:'test@cognizant.com',mobile:'000000'},
{id:$scope.myId++,name:'andefined',mail:'undefined@cognizant.com',mobile:'1111'}];
});
contactManager.controller('addContactCtrl',
function addContactCtrl($scope,$location){
$scope.contact = {};
$scope.add = function(){
if($scope.contact.name){
$scope.contact.id = $scope.myId++; // **Increment Doesn't happen Here. It assigns the same value evertime**
$scope.contacts.push($scope.contact);
$location.url('/');
}
else{
alert('Name is mandatory');
}
};
});
$ scope.myId ++中不会发生增量!
我正在为添加到列表中的每个新联系人尝试分配ID,但ID不会增加!!
答案 0 :(得分:0)
最好使用为您提供ID的服务。您可以按如下方式创建服务:
contactManager.service('uniqueIds', function () {
var currentId = null;
return {
getNextId: function () {
if (currentId === null) {
currentId = 0;
} else {
currentId = currentId + 1;
}
return currentId;
}
}:
});
然后,您可以在控制器中使用此服务,如下所示:
contactManager.controller('contactsList', ['$scope', 'uniqueIds', function ($scope, uniqueIds) {
$scope.contacts = {
id: uniqueIds.getNextId(), //Service call
name: 'Default',
mail: 'test@abc.com',
mobile:'000000'
}, {
id: uniqueIds.getNextId(), //Service call
name: 'undefined',
mail: 'undefined@xyz.com',
mobile:'1111'
}];
});
contactManager.controller('addContactCtrl', ['$scope', '$location', 'uniqueIds', function ($scope, $location, uniqueIds) {
$scope.contact = {};
$scope.add = function(){
if($scope.contact.name){
$scope.contact.id = uniqueIds.getNextId(); //Service call
$scope.contacts.push($scope.contact);
$location.url('/');
} else {
alert('Name is mandatory');
}
};
});
编辑:如果您要生成uniqueIds,那么这不是可行的方法 - 您可能需要检查this以生成它们。