0
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 并没有增加!

4

1 回答 1

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,那么这不是要走的路 - 您可能需要检查一下以生成它们。

于 2013-06-18T08:44:24.007 回答