我正在尝试创建一个自定义Angular指令,该指令使用KineticJS基于范围中的值在画布上绘制。我打算创建一个服务,然后根据接收JSON响应的$ http调用更新范围。在那一点上,我希望指令遍历范围中的值并为每个值创建一个动态节点。
但是,我不确定我是应该在控制器内还是在指令的链接功能中执行此操作。如果我要在链接功能中进行更新,我会调整范围。$ watch还是别的什么?
我已经创建了这样的自定义指令:
angular.module('history.directives', [])
.directive('kinetic', function() {
var kineticContainer = '<div id="container"></div>';
return {
restrict: 'E',
compile:function (tElement, tAttrs, transclude) {
tElement.html(kineticContainer);
},
controller: KineticCtrl
};
});
然后控制器看起来像这样:
function KineticCtrl($scope) {
$scope.stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight - $('.navbar').outerHeight()
});
$scope.drawNode = function(posx, posy) {
var layer = new Kinetic.Layer();
var group = new Kinetic.Group({
x: posx,
y: posy
});
var line = new Kinetic.Line({
points: [0, 25, 500, 25],
stroke: 'black',
strokeWidth: 4
});
var text = new Kinetic.Text({
text: 'www.google.com',
fontSize: 18,
fontFamily: 'FontAwesome',
fill: '#555',
width: 300
});
group.add(line);
group.add(text);
layer.add(group);
$scope.stage.add(layer);
};
$scope.drawNode(200, 400);
$scope.drawNode(800, 400);
$scope.drawNode(400, 100);
}
任何帮助将不胜感激!
答案 0 :(得分:1)
请参阅Difference between the 'controller', 'link' and 'compile' functions when defining a directive
总之,指令的控制器和链接功能之间几乎没有区别。控制器将首先运行,如果这很重要,但我不认为它在这里 - 因为你通过$ http检索数据,你将不得不在控制器或链接功能中使用$ watch,以便在数据变得可用。