我有一个字符串和按钮列表,它们可以更改本地范围内每个字符串的颜色属性。每个新添加的字符串都是黑色的,因为从 Controller 范围获取颜色属性。如何在新字符串的本地范围内初始化颜色属性?
这只是一个演示我的问题的例子。因此,在实际项目中,我无法将新属性添加到列表(例如 currentColor: 'Red')或其他内容。我只想知道:创建此范围时如何为本地范围内的属性设置值。
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>