I'm trying to create a custom Angular directive that uses KineticJS to draw on a canvas based off values in the scope. I intend to create a service that will then update the scope based off a $http call that receives a JSON response. At that point I'd like the directive to loop through the values in the scope and create a kinetic node for each value.
However, I'm not sure if I should be doing this inside the controller or within the link function of the directive. If I were to do the updating inside the linking function, would I scope.$watch or something else?
I've created the custom directive like this:
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
};
});
The controller then looks like this:
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);
}
Any help would be appreciated!
See Difference between the 'controller' and 'link' functions when defining an angular.js directive
In summary, there is little difference between a directive's controller and link functions. The controller will run first, if that matters, but I don't think it does here – since you are retrieving data via $http you'll have to use $watch in the controller or link function in order to trigger your logic when the data becomes available.