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

时间:2017-06-06 14:08:50

标签: angularjs scope ng-style

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

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

这是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小提琴不起作用: http://jsfiddle.net/avboivin/0qov365b/4/

1 个答案:

答案 0 :(得分:2)

&#39; - &#39;有问题,请尝试将其删除

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