模型更改时更新 ngClass 指令中的 class 名称

Updating class name in ngClass directive when model changes

我正在使用 AngularJS 和 Bootstrap 网格来显示一些需要更新的信息 real-time。但是,这也应该更新 bootstrap 列大小和偏移量。我有两个嵌套的重复,我访问祖父母范围中的数据(由于重复创建的 child 范围):

<div class="col-xs-{{$parent.$parent.colWidth}}" ng-repeat="w in $parent.widths track by $index" ng-class="{'col-xs-offset-{{$parent.$parent.colOffset}}':$first}">

更新$scope.colOffset时出现问题:col-xs-offset-[value]中的[value]不受影响。但是,如果我向 $scope.widths 添加元素,则新创建的元素具有正确的值,而原始元素具有过时的值。

我正在使用 $watch 来跟踪 $scope.plate.width 中的变化(这是变化的值)并更新相关变量 $scope.colOffset, $scope.colWidth, $scope.widths:

$scope.$watch('plate.width', function(newValue, oldValue) {
    var newValue = parseInt(newValue);
    $scope.colWidth = Math.floor(Math.min(12 / newValue, 12));
    $scope.colOffset = Math.floor((12 - $scope.colWidth * newValue) / 2);
    $scope.widths = $scope.getNumber(newValue);
});
$scope.getNumber = function(n) {
    var ar = new Array(n);
    return ar;
}

这里有趣的是 col-xs-[value] 已更新,但 col-xs-offset-[value] 未更新。

来自 AngularJS ngClass 文档 (https://docs.angularjs.org/api/ng/directive/ngClass):

When the expression changes, the previously added classes are removed and only then are the new classes added.

您可以添加 col-xs-offset-[value] 作为默认值 class 并附加另一个 class,例如col-xs-first 对于第一列,如果这能解决您的问题。