0

这是我的指令,它似乎在第一次加载时工作正常:

app.directive('myBar',function(){
        return{
            restrict: 'E',
            replace: true,
            template: '<div class="container" style="border-right:2px #9E9E9E dotted;width:102px;height:17px;"><div class="box max" style="width: {{max}}px;z-index:-1;"></div><div class="box" style="width: {{current}}px; margin-top:-20px;z-index:99999999;" ng-class="{\'greater\': current >= max, \'less\': current < max}"">{{current}}</div></div>',
            scope : {
                current: '@',
                max: '@'
            }
        };
    });

但是当我试图改变当前/最大值的值时,颜色并没有改变:

var app = angular.module('MyTutorialApp', []);
    app.controller("controller", function ($scope) {
        $scope.chargeability = [{ date: '15-Sep-13', max: 100, current: 50 },
        { date: '30-Sep-13', max: 100, current: 100 },
        { date: '15-Oct-13', max: 80, current: 50}];
        $scope.ytd = 122;
    });

在第一次加载时...这似乎工作正常,但是当我尝试更改 max 和/或 current 的值时存在问题...它不再遵循模板内的 ng-class...

ng-class="{\'greater\': current >= max, \'less\': current < max}

我缺少什么吗?感谢您提出解决问题的想法

4

2 回答 2

0

您的代码运行良好。要测试它,请使用$timeout. 这实际上是我所做的:

app.controller('myCtrl', ['$scope','$timeout', function ($scope, $timeout) {
    $scope.chargeability = [{
        date: '15-Sep-13',
        max: 100,
        current: 10
    }, {
        date: '30-Sep-13',
        max: 60,
        current: 0
    }, {
        date: '15-Oct-13',
        max: 80,
        current: 10
    }];

    $scope.ytd = 122;

 var stop;
  $scope.increase = function() {
    stop = $timeout(function() {
    // console.log($scope.chargeability[0].current);
             if ($scope.chargeability[0].current < $scope.chargeability[0].max) {
                 $scope.chargeability[0].current = $scope.chargeability[0].current + 1;
              $scope.increase();
           } else {
               $timeout.cancel(stop);
             }
    }, 100);
  };
}]);



app.directive('myBar', function () {
    return {
        restrict: 'E',
        scope: {
            current: '@',
            max: '@'
        },
        template: '<div class="container" style="width:102px;height:17px;"><div class="box max" style="width: {{max}}px;z-index:-1;"></div><div class="box" style="width: {{current}}px; margin-top:-20px;z-index:99999999;" ng-class="{\'greater\': current >= max, \'less\': current < max}""></div></div>',
        replace: true
    };
});

演示Plunker

于 2013-10-25T07:10:19.573 回答
0

当您更新 current 和 max 的值时,您可能需要调用 $apply() 来强制 angular 执行摘要循环

$scope.$apply(function() {
 // update values here, for example..
 $scope.current = newCurrentVal;
 $scope.max = newMaxVal;
});
于 2013-10-25T05:17:24.573 回答