![](/img/trans.png)
[英]Updating a form input name value after a $scope.$watch is triggered
[英]scope.$watch does not get triggered after scope.$digest in karma unit test
我要测试此指令:
.directive('mwIcon', function () {
return {
restrict: 'A',
scope: {
mwIcon: '@',
tooltip: '@',
placement: '@',
style: '@'
},
template: '<i ng-class="iconClasses" style="{{style}}" mw-tooltip="{{tooltip}}" placement="{{placement}}"></i>',
link: function (scope, el) {
el.addClass('mw-icon');
//set icon classes
scope.$watch('mwIcon', function (newVal) {
if (newVal) {
var isFontAwesome = angular.isArray(scope.mwIcon.match(/^fa-/)),
isRlnIcon = angular.isArray(scope.mwIcon.match(/rln-icon/));
if (isFontAwesome) {
scope.iconClasses = 'fa ' + scope.mwIcon;
} else if (isRlnIcon) {
scope.iconClasses = 'rln-icon ' + scope.mwIcon;
} else {
scope.iconClasses = 'glyphicon glyphicon-' + scope.mwIcon;
}
}
});
}
};
})
具体来说,当我更改scope.mwIcon
时会发生什么。 它也应该更改<i>
元素的类,因为scope.mwIcon
具有观察者,对吗? 这是我的测试:
it('should change the class according to the new icon', function () {
var icon = '<span mw-icon="search"></span>';
var el = $compile(icon)(scope);
scope.$digest();
expect(el.children().hasClass("glyphicon")).toBe(true);
expect(el.children().hasClass("glyphicon-search")).toBe(true);
scope.mwIcon = "fa-star";
scope.$digest();
expect(el.children().hasClass("fa")).toBe(true);
expect(el.children().hasClass("fa-star")).toBe(true);
});
即使我使用scope.$digest
触发了scope.mwIcon
的更改,底部的两个断言仍返回false。 为什么我的<i>
元素仍然具有“ glyphicon glyphicon-search”类而不是“ fa fa-star”类的想法?
您将mwIcon绑定到属性字符串(带有@),因此随后设置scope.mwIcon不会触发$ watch。 您可以将其更改为双向绑定(mwIcon:'=',),也可以尝试使用attr。$ observe代替,将attrs作为第三个arg添加到链接函数中,尽管我没有尝试过最后一种方法。
问题在于该指令正在使用隔离范围。 在隔离范围上设置新的mwIcon
时,该测试有效。
it('should change the class according to the new icon', function () {
var icon = '<span mw-icon="search"></span>';
var el = $compile(icon)(scope);
var isolatedScope = el.isolateScope();
scope.$digest();
expect(el.children().hasClass("glyphicon")).toBe(true);
expect(el.children().hasClass("glyphicon-search")).toBe(true);
isolatedScope.mwIcon = "fa-star";
scope.$digest();
expect(el.children().hasClass("fa")).toBe(true);
expect(el.children().hasClass("fa-star")).toBe(true);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.