nat*_*asm 13 angularjs angularjs-directive
我有一个指令,它使用隔离范围将数据传递给随时间变化的指令.它会监视该值的变化,并对每次更改进行一些计算.当我尝试对指令进行单元测试时,我无法触发手表(为简洁而修剪,但基本概念如下所示):
指示:
angular.module('directives.file', [])
.directive('file', function() {
return {
restrict: 'E',
scope: {
data: '=',
filename: '@',
},
link: function(scope, element, attrs) {
console.log('in link');
var convertToCSV = function(newItem) { ... };
scope.$watch('data', function(newItem) {
console.log('in watch');
var csv_obj = convertToCSV(newItem);
var blob = new Blob([csv_obj], {type:'text/plain'});
var link = window.webkitURL.createObjectURL(blob);
element.html('<a href=' + link + ' download=' + attrs.filename +'>Export to CSV</a>');
}, true);
}
};
});
Run Code Online (Sandbox Code Playgroud)
测试:
describe('Unit: File export', function() {
var scope;
beforeEach(module('directives.file'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
};
it('should create a CSV', function() {
scope.input = someData;
var e = $compile('<file data="input" filename="filename.csv"></file>')(scope);
//I've also tried below but that does not help
scope.$apply(function() { scope.input = {}; });
});
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能触发手表,以便触发我的"In watch"调试语句?我编译时会触发"链接".
Mic*_*ord 16
对于$watch得到触发,必须在它被定义的范围或其父发生消化周期.由于您的指令创建了隔离范围,因此它不会从父范围继承,因此在您调用$apply适当的范围之前,它的观察者不会被处理.
您可以通过调用服务scope()返回的元素来访问指令范围$compile:
scope.input = someData;
var e = $compile('<file data="input" filename="filename.csv"></file>')(scope);
e.isolateScope().$apply();
Run Code Online (Sandbox Code Playgroud)
这个jsFiddler举例说明了这一点.
| 归档时间: |
|
| 查看次数: |
10000 次 |
| 最近记录: |