在angularjs中创建一个二维数组

时间:2014-04-03 10:24:44

标签: angularjs multidimensional-array

最初我将我的ng风格设置为:

<div ng-repeat="row in rowArray">
   <div ng-repeat = "col in colarray">

    <span ng-style="my_array[i]" >Some Text </span>
   </div>
</div>

如果rowArray中有2行,columnArray中有3列, 在决赛中我需要类似的东西,

<div><div>
   <span ng-style="my_array[0][0]" >Some Text </span>
   <span ng-style="my_array[0][1]" >Some Text </span>
   <span ng-style="my_array[0][2]" >This color need to be changed </span>
   <span ng-style="my_array[1][0]" >Some Text </span>
   <span ng-style="my_array[1][1]" >Some Text </span>
   <span ng-style="my_array[1][2]" >Some Text </span>
</div></div>

我有一个这样的按钮, <input type="button" ng-click="change_style(my_array[0][2])" /> 并定义了类似

的内容
$scope.change_style = function(){

}

如何更改传递给此函数的参数的颜色。

1 个答案:

答案 0 :(得分:0)

看看这个

<强> Working Demo

<强> HTML

<div ng-controller="MyCtrl">
    <div ng-repeat="row in rowArray">
       <div ng-repeat="col in colarray"> 
         <span ng-style="my_array[$parent.$index][$index]">
               {{data[$parent.$index][$index]}}
               <input type="button" value="Change" ng-click="change_style(my_array[$parent.$index][$index])" />
         </span>
       </div>
    </div>
</div>

<强> SCRIPT

function MyCtrl($scope) {
    $scope.rowArray = ['r1', 'r2'];
    $scope.colarray = ["c1", "c2", "c3"];
    $scope.data = [
        ["Text-00", "Text-01", "Text-02"],
        ["Text-10", "Text-11", "Text-12"]
    ];

    $scope.my_array = [
        [{
            id: 12,
            color: 'green'
        }, {
            id: 13,
            color: 'blue'
        }, {
            id: 14,
            color: 'red'
        }],
        [{
            id: 15,
            color: 'green'
        }, {
            id: 16,
            color: 'brown'
        }, {
            id: 17,
            color: 'red'
        }]
    ];

    $scope.change_style = function (obj) {
        $scope.yourColor = "blue";
        $scope.my_array = $scope.my_array.map(function (c, row) {
            return c.map(function (data) {
                if (data.id == obj.id) {
                    return {
                        id: 12,
                        color: $scope.yourColor
                    };
                } else {
                    return data;
                }
            });
        });
    }
}