3
\$\begingroup\$

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 = '<canvas></canvas>';

        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: <yup-canvas></yup-canvas>

Fire away! :)

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

I never used compile: so I am not sure what you use it for but.. I think there is a template property in directives and you can easily access the canvas with .children[0]

app.directive('yupCanvas', function factory() {

    return {

        restrict: 'E',
        template: '<canvas></canvas>',
        link: function(scope, element, attrs) {
          var canvas = new fabric.Canvas(element.children[0], {
            isDrawingMode: true
          });

        }
    };
});

Maybe I am not understanding what you are trying to do though...

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.