ng-style 从 $index 分配动态范围变量

ng-style assign dynamic scope variable from $index

我正在尝试将范围变量的值分配给 ng-style 指令,但名称未被解析。

我做错了什么?当您按下 TEST 按钮时,它应该将文本变为红色,但范围变量未被解析,因为它的名称是动态的。我尝试了多种不同的语法,但都不起作用。

这是html:

<div ng-app="myApp" ng-controller="MyCtrl">  
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
   <div ng-style="{{'DynamicVariable-'+$index}}">
    {{someone.name}}
   </div>
  </div>
</div>

控制器代码

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    name: 'John'
  };
$scope.items=[1,2,3,4,5,6,7,8,9];
  $scope.mainId = 1;
  $scope.Test=function(){
      for(var i=0;i<$scope.items.length;i++){
    $scope["DynamicVariable-"+i]={color:'red'};    
  }
  console.log($scope);
  };
}]);

js fiddle 不起作用: http://jsfiddle.net/avboivin/0qov365b/4/

'-'有问题,尝试删除它

html:

<div ng-app="myApp" ng-controller="MyCtrl">
    <button ng-click="Test()">test</button>
    <div ng-repeat="item in items">
        <div ng-style="{{'DynamicVariable'+$index}}">
            {{ someone.name }}
        </div>
    </div>
</div>

控制器:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.someone = {
        name: 'John'
    };
    $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    $scope.mainId = 1;
    $scope.Test = function () {
        for (var i = 0; i < $scope.items.length; i++) {
            $scope["DynamicVariable" + i] = { color: 'red' };
        }
        console.log($scope);
    };
}]);

fork