颜色不会根据current / max的值而改变

时间:2013-10-25 04:07:39

标签: angularjs angularjs-directive

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

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 ... < / p>

ng-class="{\'greater\': current >= max, \'less\': current < max}
我缺少什么吗?感谢您提出解决问题的想法

2 个答案:

答案 0 :(得分:0)

当您更新当前值和最大值时,您可能需要调用$ apply()来强制角度进行摘要循环

$scope.$apply(function() {
 // update values here, for example..
 $scope.current = newCurrentVal;
 $scope.max = newMaxVal;
});

答案 1 :(得分: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