将数据绑定的HTML类链接到指令

时间:2014-04-10 20:49:41

标签: javascript angularjs angularjs-directive jasmine

所以基本上我希望在指令上切换“order-asc”和“order-desc”类。我现在已经取消了切换部分。

我有以下测试:

describe('OfferList sorters', function() {
  'use strict';
  beforeEach(module('offerListSorters'));

  describe('sorter directive', function() {
    var element, scope, parentScope;
    beforeEach(inject(function ($compile, $rootScope){
      parentScope = $rootScope.$new();
      element = angular.element('<sorter order-by="location">{{2+2}}</sorter>');
      $compile(element)(parentScope);
      scope = element.isolateScope();
      parentScope.$digest();
    }));

    it('should contain 4', function() {
      expect(element.html()).toBe('4');
    });

    it('should have asc/desc state on scope', function(){
      expect(scope.isAscending).toBeDefined();
    });

    it('should have class order-asc by default', function() {
      expect(element).toHaveClass('order-asc');
    });
  });
});

我有以下指令:

offerListSorters.directive('sorter', [function (){
  return {
    scope: {},
    controller: function($scope, $element, $attrs, $transclude) {
      $scope.isAscending = true;
    },
    link: function($scope, iElm, iAttrs, controller) {
      iElm.addClass('order-{{isAscending ? \'asc\' : \'desc\'}}');
    }
  };
}]);

我发现最后一次测试失败了。 {{}}绑定逐字添加到类属性中。我还在指令链接函数中尝试了以下行,没有结果:

iElm.attr('ng-class', 'isAscending ? \'asc\' : \'desc\'');
iAttrs.$set('ngClass', 'isAscending ? \'asc\' : \'desc\'');

我尝试将$scope.$digest();添加到链接功能的末尾。但我无处可去。

我可以解决它,因为它已完成here或通过做一些$ scope。$ watch magic in link function,但我真的很想理解为什么我目前正在尝试的不起作用。

1 个答案:

答案 0 :(得分:1)

为什么不使用ng-class?

<div sorter ng-class="{'asc' : isAscending, 'desc' : !isAscending}"></sorter>

在addClass等中添加绑定是行不通的,因为当$使用$ interpolate和$ parse来检测DOM /模板中的绑定/指令时,在$ compile pahse期间添加了绑定逻辑。之后添加时,angular会将其视为普通字符串。