【问题标题】:ng-style assign dynamic scope variable from $indexng-style 从 $index 分配动态范围变量
【发布时间】:2017-06-06 22:21:12
【问题描述】:

我正在尝试将范围变量的值分配给 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 小提琴不起作用: http://jsfiddle.net/avboivin/0qov365b/4/

【问题讨论】:

    标签: angularjs scope ng-style


    【解决方案1】:

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

    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

    【讨论】:

    • 哈哈。我正在寻找最近的墙角我可以撞到我的头
    猜你喜欢
    • 2016-12-24
    • 2016-11-28
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多