我有一个如下指令:
angular.module('buttonModule',[]).directive('saveButton',[ function () { function resetButton(element) { element.removeClass('btn-primary'); } return { restrict: 'E',replace: 'false',scope: { isSave: '=' },template: '<button class="btn" href="#" style="margin-right:10px;" ng-disabled="!isSave">' + '</button>',link: function (scope,element) { console.log(scope.isSave); scope.$watch('isSave',function () { if (scope.isSave) { resetButton(scope,element); } }); } }; } ]);
和茉莉花测试如下:
describe('Directives: saveButton',function() { var scope,compile; beforeEach(module('buttonModule')); beforeEach(inject(function($compile,$rootScope) { scope = $rootScope.$new(); compile = $compile; })); function createDirective() { var elem,compiledElem; elem = angular.element('<save-button></save-button>'); compiledElem = compile(elem)(scope); scope.$digest(); return compiledElem; } it('should set button clean',function() { var el = createDirective(); el.scope().isSaving = true; expect(el.hasClass('btn-primary')).toBeFalsy(); }); });
问题是isSaving的值没有反映在指令中,因此从不调用resetButton函数.如何访问规范中的指令范围并更改变量值.我尝试使用isolateScope,但同样的问题仍然存在.
解决方法
首先请注意,当您只接受一个参数时,您使用两个参数调用resetButton函数.我在我的示例代码中解决了这个问题我还在按钮元素中添加了类btn-primary,以使测试更清晰.
您的指令是在外部作用域和隔离作用域之间设置双向数据绑定:
scope: { isDirty: '=',isSaving: '=' }
您应该利用它来修改isSaving变量.
elem = '<save-button is-saving="isSaving"></save-button>';
然后修改编译时使用的作用域的isSaving属性(您还需要触发摘要循环以使观察者检测到更改):
var el = createDirective(); scope.isSaving = true; scope.$apply(); expect(el.hasClass('btn-primary')).toBeFalsy();
演示:http://plnkr.co/edit/Fr08guUMIxTLYTY0wTW3?p=preview
如果您不想将is-saving属性添加到元素中,并且仍想修改变量,则需要检索隔离范围:
var el = createDirective(); var isolatedScope = el.isolateScope(); isolatedScope.isSaving = true; isolatedScope.$apply(); expect(el.hasClass('btn-primary')).toBeFalsy();
为此,您需要删除与isSaving的双向绑定:
scope: { isDirty: '=' }
否则它将尝试绑定到不存在的东西,因为元素上没有is-saving属性,您将收到以下错误:
Expression ‘undefined’ used with directive ‘saveButton’ is
non-assignable!
(07001$compile/nonassign?p0=undefined&p1=saveButton)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。