【问题标题】:Updating class name in ngClass directive when model changes模型更改时更新 ngClass 指令中的类名
【发布时间】:2015-07-01 16:50:50
【问题描述】:

我正在使用 AngularJS 和 Bootstrap 网格来呈现一些需要实时更新的信息。但是,这也应该更新引导列的大小和偏移量。我有两个嵌套重复,我访问祖父范围中的数据(由于重复创建的子范围):

<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] 未更新。

【问题讨论】:

    标签: javascript angularjs twitter-bootstrap ng-class


    【解决方案1】:

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

    当表达式改变时,之前添加的类会被移除,然后才会添加新的类。

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

    【讨论】:

    • 受您的回答启发,我按以下方式编辑了 div:&lt;div class="col-xs-{{$parent.$parent.colWidth}} col-xs-offset-{{$parent.$parent.colOffset * $first}}" ng-repeat="w in $parent.widths track by $index"&gt;
    • 此行为可能是由于更改键值未触发“表达式更改”。
    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2015-11-02
    • 2018-07-18
    相关资源
    最近更新 更多