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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With