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
source share