HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

First angularjs directive

Submitted by: @import:stackexchange-codereview··
0
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.

  • 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 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.