Reputation: 63
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>
Upvotes: 0
Views: 2792
Reputation: 136134
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.
Upvotes: 2
Reputation: 3104
ng-repeat
creates it's own code. To initialize the local scope you can use ng-init
.
<div ng-repeat="item in list" ng-init="color = 'red'">
<span style="color:{{color}}">{{item.text}}</span>
</div>
Upvotes: 1
Reputation: 1624
Make $scope.list an array of objects which contain both the text and color.
$scope.list = [
{ text: 'text1',color: 'black' },
{ text: 'text2',color: 'black' },
{ text: 'text3',color: 'black' }
]
Html:
<span style="color:{{item.color}}">{{item.text}}</span>
<button data-ng-click="item.color = 'Red'">Red</button>
If you want initialize without list, You want to use $watch.
$scope.$watch('list', function() {
$scope.color = 'black';
console.log('list has changed, do whatever you want');
});
Upvotes: 0