ng-style不工作/更新

时间:2017-01-09 21:37:17

标签: javascript css angularjs

我的html文件中有此代码。我想显示一个方形游戏板,ng-style在程序运行时更新background-color

<div class="row" ng-repeat="col in board">
        <div class="column" ng-style="{'background-color': colour($parent.$index, $index)}" ng-repeat="row in col track by $index"></div>
</div>

现在colour函数只返回一种颜色,board就是这样设置的:

function setUp() {
    $scope.board=[];
    for (var i = 0; i < BOARD_SIZE; i++) {
        $scope.board[i] = [];
        for (var j = 0; j < BOARD_SIZE; j++) {
            $scope.board[i][j] = false;
        }
    }
}

$scope.colour = function(col, row) {
    return '#e6e6e6';
}
当我尝试运行时,

没有任何显示。我希望它能在屏幕上显示一个正方形。

2 个答案:

答案 0 :(得分:0)

你的内部div(你正在应用ng风格的那个)没有内容。因此,除非您添加内容或另外将其设置为具有宽度和高度,否则它将不会显示。

答案 1 :(得分:0)

问题似乎是子div中缺少的内容(第二次ng-repeat)。

function MyController($scope) {
    var BOARD_SIZE = 10;

    function setUp() {
        $scope.board = [];
        for (var i = 0; i < BOARD_SIZE; i++) {
            $scope.board[i] = [];
            for (var j = 0; j < BOARD_SIZE; j++) {
                $scope.board[i][j] = false;
            }
        }
    }

    $scope.colour = function (col, row) {
        return '#e6e6e6';
    }

    setUp();

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyController">
    <div class="row" ng-repeat="col in board">
        <div class="column" ng-style="{'background-color': colour($parent.$index, $index)}" ng-repeat="row in col track by $index">{{row}}</div>
    </div>
</div>

如果您不打算插入内容,则应修复高度和宽度(我使用了column类)

function MyController($scope) {
    var BOARD_SIZE = 10;

    function setUp() {
        $scope.board = [];
        for (var i = 0; i < BOARD_SIZE; i++) {
            $scope.board[i] = [];
            for (var j = 0; j < BOARD_SIZE; j++) {
                $scope.board[i][j] = false;
            }
        }
    }

    $scope.colour = function (col, row) {
        return '#e6e6e6';
    }

    setUp();

}
.column {
    height: 20px;
    width: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyController">
    <div class="row" ng-repeat="col in board">
        <div class="column" ng-style="{'background-color': colour($parent.$index, $index)}" ng-repeat="row in col track by $index"></div>
    </div>
</div>