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');
        }
    };
});

Increment doesn't happen in $scope.myId++ !

I'm trying the assign id's to every new contact added to the list, but the id's are not getting incremented !!

sakthi
  • 929
  • 6
  • 18
  • 1
    Your addContactCtrl has no idea what $scope.myId is, so it can't increment it. You've declared $scope.myId in the contactsList controller, not addContactCtrl – PaReeOhNos Jun 18 '13 at 08:07

1 Answers1

0

You are better off using a service that provides the ID for you. You can create a service as follows:

contactManager.service('uniqueIds', function () {
    var currentId = null;

    return {
        getNextId: function () {
            if (currentId === null) {
                currentId = 0;
            } else {
                currentId = currentId + 1;
            }
            return currentId;
        }
    }:
});

You can then use this service in your controllers as follows:

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');
        }
    };
});

EDIT: If you are looking to generate uniqueIds, then this is not the way to go - You may want to check this out to generate them.

Community
  • 1
  • 1
callmekatootie
  • 10,989
  • 15
  • 69
  • 104