I am using the following example
https://docs.angularjs.org/api/ng/directive/ngController
in the above mentioned example I have added new button called save. In save I am trying to push all the contacts into an array. Following is my code for Save.
$scope.SaveContact = function () {
var len = $scope.contacts.length;
var contactlist = [];
angular.foreach($scope.contacts, function (value, key) {
contactlist.push( value.type + ':' + key);
}, contactlist);
console.log(contactlist);
};
Please can someone help me solve this.
You should fix the spelling of .foreach first.
Since you are iterating over an array, the key will be the index, and the value will be the object stored in the array. You are also doing a string concat (key +":"+ value) so you will get an array like this:
I would suggest using the Array prototype .forEach instead of the angular .forEach, since you don't need to use the keys (array index in this case).
If you want to use angular.forEach I would say:
But I don't recommend it since it's easy to confuse the value parameter in the angular.forEach callback with the "value" key of the objects stored in the $scope.contacts array.
I assumed you are using the following format for $scope.contacts from the angular documentation:
This way, you should get an array like this:
Also, I would suggest using $scope.contactlist instead of var contactlist, so the list is accessible outside the SaveContact function.