Javascript 将数据绑定HTML类链接到指令
所以基本上我想让类“order asc”和“order desc”在指令上切换。我现在已经把开关的部分报废了 我有以下测试:Javascript 将数据绑定HTML类链接到指令,javascript,angularjs,angularjs-directive,jasmine,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;
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');
});
});
});
我发现最后一次考试失败了。{{}
绑定被逐字添加到class属性中。我还尝试了指令链接函数中的以下行,但没有结果:
iElm.attr('ng-class', 'isAscending ? \'asc\' : \'desc\'');
iAttrs.$set('ngClass', 'isAscending ? \'asc\' : \'desc\'');
我已尝试添加$scope.$digest()代码>到链接函数的末尾。但我什么也没得到
我可以按原样或通过在link函数中使用$scope.$watch magic来解决它,但我真的很想了解为什么我目前尝试的方法不起作用。为什么不使用ng类呢
<div sorter ng-class="{'asc' : isAscending, 'desc' : !isAscending}"></sorter>
在addClass等中添加绑定不起作用,因为绑定逻辑是在$compile pahse期间添加的,angular使用$interpolate和$parse检测DOM/模板中的绑定/指令。之后添加时,angular将其视为普通字符串。我希望能够将我的分类器简单地定义为一些文本。处理类的逻辑应该由指令处理。例如,我应该使用compile函数而不是link函数吗?angular的一个重要部分是逻辑在标记中可见。无论如何,还有其他选择。如何定义排序顺序是asc还是desc?是点菜吗?不是。它只是在隔离范围上定义的一个可切换值。该指令的元素将有一个单击绑定,用于切换isAscending值。选择使用模板,按照您的建议保持标记中的逻辑可见。谢谢
<div sorter ng-class="{'asc' : isAscending, 'desc' : !isAscending}"></sorter>