I have a list of strings and buttons that change color property of each string in local scope. Every new added string will be black, because get color property from Controller scope. How can initialize color property in local scope of new string?
It is just a example to demonstrate my problem. So, in real project I can’t add new property to List (like currentColor: 'Red'), or something else. I just want to know: How can I set value to property in local scope when this scope creating.
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyController', function ($scope) {
$scope.color = 'Black';
$scope.list = [
{ text: 'text1' },
{ text: 'text2' },
{ text: 'text3' }
]
$scope.AddNewText = function () {
$scope.list.push({ text: 'text' + ($scope.list.length + 1) });
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyController">
<div ng-repeat="item in list">
<span style="color:{{color}}">{{item.text}}</span>
<button data-ng-click="color = 'Red'">Red</button>
<button data-ng-click="color = 'Green'">Green</button>
<button data-ng-click="color = 'Blue'">Blue</button>
<button data-ng-click="color = 'Black'">Black</button>
</div>
<button data-ng-click="AddNewText()">Add new text</button>
</div>
</div>
Only change one html line that will handle the default value of color by using ng-style
directive.
<span ng-style="{'color':color||'Black'}">{{item.text}}</span>
You html will look like below
<div ng-app="MyApp">
<div ng-controller="MyController">
<div ng-repeat="item in list">
<span ng-style="{'color':color||'Black'}">{{item.text}}</span>
<button data-ng-click="color = 'Red'">Red</button>
<button data-ng-click="color = 'Green'">Green</button>
<button data-ng-click="color = 'Blue'">Blue</button>
<button data-ng-click="color = 'Black'">Black</button>
</div>
<button data-ng-click="AddNewText()">Add new text</button>
</div>
</div>
No need to set any color value from the controller. Fiddle here
Hopefully I understand your problem. Thanks.