0

好吧,我真的很菜鸟,所以我问这是正确的方法还是有更简单的方法。

我想要的是根据值向元素添加一个类......所以我接下来要做的是:

HTML:

<progress value="{{ luminaria.nivelcargabateria }}"></progress>

指令定义:

angular.module('angularJSApp')
  .directive('progress', function () {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'views/progress.html',
      scope: {
        value: '@'
      },
      controller: function ($scope) {
        $scope.barClass = function () {
          return ($scope.value > 66)?'success':($scope.value > 33)?'warning':'danger';
      }
    }
  };
});

指令模板:

<div class="progress">
  <div class="progress-bar progress-bar-{{ barClass() }}" role="progressbar" aria-valuenow="{{ value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ value }}%">
  <span class="sr-only">{{ value }}%</span>
</div>

4

3 回答 3

1

您可以使用非常方便的ng-class指令http://docs.angularjs.org/api/ng.directive:ngClass

例如

<div ng-class="success: aboutToFinish(), warning: inProgress(), danger: justStarted()"></div>

在控制器内部:

$scope.aboutToFinish = function() {
  return $scope.value > 66;
}

$scope.inProgress = function() {
  return $scope.value > 33 && $scope.value < 66;
}

$scope.justStarted = function() {
  return !($scope.inProgress() && $scope.finished());
}

恕我直言,这个解决方案将更具可读性和可维护性,您可以毫不费力地为这件作品编写单元测试。

于 2013-08-22T15:27:54.967 回答
0

我不确定它是否更好,但您也可以使用ng-class它:

angular.module('angularJSApp')
  .directive('progress', function () {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'views/progress.html',
      scope: {
        value: '@'
      }
    }
  };
});

HTML:进度条-{{ barClass() }}

<div class="progress">
  <div class="progress-bar" ng-class="{'progress-bar-success': value>66, 'progress-bar-danger': value>33, 'progress-bar-danger': value<=33}" role="progressbar" aria-valuenow="{{ value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ value }}%">
  <span class="sr-only">{{ value }}%</span>
</div>
于 2013-08-22T15:27:25.583 回答
0

这很容易,使用ng-class

<div ng-class="{'class-a': testCondition, 'class-b': anotherTestCondition}"></div>
于 2013-08-22T15:27:36.607 回答