Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot push object in an array using forEach loop in angular

I am trying to input some color name and if the color is not present in the list it should get added to it and the li element should also get that particular color. I dont understand whats wrong with 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>
like image 575
user3621573 Avatar asked Oct 31 '22 03:10

user3621573


1 Answers

You have at least 3 issues.

Issue #1. Put ngClick button within controller container otherwise 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>

Issue #2. You need to push an object into array, not a string:

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

Issue #3. Checking for object existence in array is currently not correct. You would better use either 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, minor one: remove </input> - input elements don't have closing tags (because they don't have content).

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

like image 81
dfsq Avatar answered Nov 12 '22 09:11

dfsq