patternjavascriptMinor
First angularjs directive
Viewed 0 times
directiveangularjsfirst
Problem
I've just written my first angularjs directive, and I was hoping to get some feedback. I already have two doubts myself.
Here's the code:
And I'm simply calling the directive like so: ``
Fire away! :)
- Why is it that I must use
tElement.append()to append the canvas element?tElement.html()doesn't work, at all. That just returns[[object HTMLCanvasElement]]in plain text inside of the element.
- Should I be accessing
canvasElement[0]? It feels wrong, but it might not be.
Here's the code:
angular.module('yupDraw', [])
.directive('yupCanvas', function factory() {
// Create elements (templates) in vars here
var canvasTemplate = '';
return {
restrict: 'E',
compile: function compile(tElement, tAttrs, transclude) {
var canvasElement = angular.element(canvasTemplate);
tElement.append(canvasElement);
return function link(scope, element, attrs) {
var canvas = new fabric.Canvas(canvasElement[0], {
isDrawingMode: true
});
}
}
};
});
And I'm simply calling the directive like so: ``
Fire away! :)
Solution
Angular includes a tiny subset of jQuery called
One solution would be to use jquery. If you include jquery before angular, angular will use your jquery instead of the embedded jqlite. Swap the script tags in this fiddle to see it toggle between working and not.
Another solution would be to use the outerHTML of your canvas element's html node like in this fiddle:
I think using canvasElement[0] is fine.
jqLite which is what you get with angular.element. The html() method on it specifically only accepts a string, not an array of jqLite objects like jQuery normally does I think (unless it's a bug).One solution would be to use jquery. If you include jquery before angular, angular will use your jquery instead of the embedded jqlite. Swap the script tags in this fiddle to see it toggle between working and not.
Another solution would be to use the outerHTML of your canvas element's html node like in this fiddle:
tElement.html(canvasElement[0].outerHTML);I think using canvasElement[0] is fine.
Code Snippets
tElement.html(canvasElement[0].outerHTML);Context
StackExchange Code Review Q#31444, answer score: 3
Revisions (0)
No revisions yet.