我有一个angularjs指令。 Image src绑定到image.src
模型。指令监视image.src
并且必须在图像完全加载时触发resizeImage
控制器的方法。
我想测试resizeImage
方法被调用,但由于image.onload
回调,我无法监视它。
此外,我再次遇到指令编译问题。我已在Can not get element in directive while testing AngularJs + Jasmine解决了这个问题,但无法强制对此新指令进行工作测试。
这是html代码:
<form name="image-data" class="col-md-12">
<textarea name="data-base64" class="form-control" rows="3" data-ng-model="image.src" placeholder="Add base64 encoded image string"> </textarea>
</form>
<div image-directive=""></div>
这是指令代码:
angular.module('app', [])
.directive('imageDirective', imageDirective);
function imageDirective ($log) {
var imgController = function ($scope, $log) {
$scope.image = {
src: null
};
this.resizeImage = function (image) {
$log.info('Runs resizeImage');
};
},
link = function (scope, el, attrs, imgController) {
var imageEl = document.getElementById('image');
scope.$watch('image.src', function () {
imageEl.onload = function () {
$log.info('Runs image.onload');
imgController.resizeImage(image);
};
});
};
return {
restrict: 'A',
link: link,
templateUrl: 'dir.html',
controller: imgController
}
}
指令模板:
<div class="image-wrapper" data-ng-show="image.src.length > 0">
<img data-ng-src="{{image.src}}" id="image" class="img-responsive" />
</div>
规格代码:
describe('Directive with image onload event', function() {
var $compile, $scope, $templateCache, $document, $log, template,
html = '<div data-canvas-directive></div>',
dirHtml = '<div class="image-wrapper" data-ng-show="image.src.length > 0"><img data-ng-src="{{image.src}}" id="image" class="img-responsive" /></div>';
beforeEach(module('app'));
beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_, _$document_){
$document = _$document_;
$compile = _$compile_;
$scope = _$rootScope_.$new();
$templateCache = _$templateCache_;
template = $templateCache.put('dir.html', dirHtml);
}));
var createDirective = function () {
var elm = angular.element(html);
$compile(elm)($scope);
document.body.appendChild(elm[0]);
$scope.$digest();
return elm;
};
describe('when created', function () {
it('should render the expected output', function () {
var element = createDirective();
expect(element.find('img').length).toBe(1);
document.body.removeChild(element[0]);
});
});
});