【发布时间】:2016-05-13 23:48:57
【问题描述】:
我正在制作一个包含画布的指令,但在我需要的所有地方都无法访问它。我目前正在指令的link 中设置画布并在其上绘制一些初始元素,但我还需要访问指令控制器中的相同画布来更新它。目前我的指令声明如下所示:
angular.module('myModule').directive('myCanvasDirective', CanvasDirective);
function CanvasDirective() {
var linker = function (scope, element, attrs) {
scope.vm.ctx = element[0].childNodes[0].getContext('2d');
//do some initial drawing using scope.vm.ctx
//this works
}
return {
priority: 1001,
restrict: 'E',
link: linker,
scope: {
displayValue: '=displayValue'
},
template: '<canvas id="myCanvas" width="80" height="80" />',
controller: MyCanvasController,
controllerAs: 'vm',
bindToController: true
};
};
function MyCanvasController() {
var vm = this;
vm.draw = function () {
vm.ctx.strokeStyle = '#808080';
//vm.ctx is unavailable here despite being attached to scope in linker
};
vm.draw();
};
如何在MyCanvasController 中访问我的画布上下文?由于多个ngRepeats,该指令将在页面上多次使用,因此我不想只使用document.getElementById()。
【问题讨论】:
标签: angularjs html canvas angularjs-directive angularjs-scope