Angularjs 是否有更简洁的 more "angular" 方法来替换指令模板中嵌入的 class 值?

Angularjs Is there a cleaner more "angular" way to replace a transcluded class value in a directive template?

下面是我能弄清楚如何获取指令以从其原始元素中提取属性、通过点击服务获取新值然后添加新服务方法的唯一方法 return作为指令模板中的 class。我想知道是否有一种替代模式可能比这种可能使用 ng-class 或可能 ng-transclude 的模式更干净:

html:

<my-directive data-condition="{{hour.condition}}"></my-directive>

js:

angular.module('myApp')
  .directive('myDirective', function (myService) {
    return {
      transclude: true,
      replace: true,
      scope: true,
      template: '<i class="{{wiIconClass}}"></i>',
      restrict: 'E',
      link: function($scope, $elm, attrs){
        $scope.wiIconClass=myService.getValue(attrs.condition);
      }
    }
  });

如果你的函数 myService.getValue 是同步的,你可以简单地做:

<div ng-class="getClass(hour.condition)">

在你的控制器中:

$scope.getClass = function(condition) {
  return myService.getValue(condition);
}


或者,您可以直接将您的服务放在您的范围内:

$scope.myService = myService;

所以 HTML 变成

<div ng-class="myService.getValue(hour.condition)">


在这两种情况下,您都需要将服务注入控制器:

myModule.controller('myController', function($scope, myService) {
  // this controller has access to myService
})

我会使用 Directives scope 参数而不是 Directives Attribute values。这是因为在使用属性时,您需要设置一个 $watch 来查看该值何时更新,使用 $scope 您可以获得绑定方面的好处。

至于如何回应最好的方式,在不了解你的实际任务的情况下很难说。您可以 Angular 以几种不同的方式更新元素 css class 的值。

这是一个可用的 Plunker,对您现有的代码进行了一些小的更新。 http://plnkr.co/edit/W0SOiBEDE03MgostqemT?p=preview

angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.hour = {
            condition: 'good'
        };
    })
    .factory('myService', function() {
        var condValues = {
            good: 'good-class',
            bad: 'bad-class'
        };
        return {
            getValue: function(key) {
                return condValues[key];
            }
        };
    })
    .directive('myDirective', function(myService) {
        return {
            transclude: true,
            replace: true,
            scope: {
                condition: '='
            },
            template: '<i class="{{myService.getValue(condition)}}"></i>',
            restrict: 'E',
            link: function(scope, elm, attrs) {
                scope.myService = myService;
            }
        };
    });