Cannot push an object in an array using forEach loop in angular

I am trying to enter a color name, and if the color is not in the list, it should be added to it, and the li element should also get that particular color. I do not understand what happened to this

<!DOCTYPE html> <html> <head></head> <body ng-app="colors"> <div ng-controller="mainCtrl as ctrl"> <ul ng-repeat="color in ctrl.colors"> <li ng-bind="color.label" ng-style="{color:color.label}"> </ul> <input type="text" ng-model="ctrl.colordisp"></input> {{ctrl.colordisp}} </div> <button type="button" ng-click="ctrl.checkColor()">submit</button> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script> angular.module("colors",[]) .controller("mainCtrl",[function(){ var self=this; self.colors=[ {label:"red"}, {label:"blue"}, {label:"green"} ]; self.colordisp="red"; self.checkColor=function(){ angular.forEach(self.colors,function(c){ if(c.label!==self.colordisp){ self.colors.push("label:"+self.colordisp); } }); }; }]); </script> </body> </html> 
+5
source share
2 answers

You have at least 3 problems.

Problem number 1. Place the ngClick button in the controller container, otherwise the click will not be detected:

 <div ng-controller="mainCtrl as ctrl"> <ul ng-repeat="color in ctrl.colors"> <li ng-bind="color.label" ng-style="{color: color.label}"> </ul> <input type="text" ng-model="ctrl.colordisp"> {{ctrl.colordisp}} <button type="button" ng-click="ctrl.checkColor()">submit</button> </div> 

Problem number 2. You need to push an object into an array, not a string:

 self.colors.push({label: self.colordisp}); 

Problem No. 3. Checking for the existence of an object in the array is currently incorrect. You better use the Array.prototype.filter or Array.prototype.some methods:

 self.checkColor = function() { var inArray = self.colors.some(function(obj) { return obj.label === self.colordisp; }); if (!inArray) { self.colors.push({label: self.colordisp}); } }; 

Finally, a minor: remove </input> - input elements do not have closing tags (because they have no content).

Demo: http://plnkr.co/edit/LBy5RCiXYApBEvuUoIdj?p=preview

+2
source

You add a string, not an object.

Change

 self.colors.push("label:"+self.colordisp); 

in

 self.colors.push({label: self.colordisp}); 

The logic is also incorrect, you have to check if the color is present, and add if it is not, for example:

  self.checkColor=function(){ var found = false; angular.forEach(self.colors,function(c){ if(c.label ===self.colordisp){ found = true; } }); if (!found) { self.colors.push({label: self.colordisp}); } } 

will do the job.

0
source

All Articles