3

I'm trying to understand how I can pass a variable or its argument of the function to a directive.

This is in my controller.

    scope.setFile = function (element) {
        var reader = new FileReader();

        reader.onload = function (event) {
            var uploadedImage = event.target.result;
        };

        // Reads the image as a data URL.
        reader.readAsDataURL(element.files[0]);
    }

I need to push the variable uploadedImage to the directive so it can update a canvas or the events argument. Code below:

  fabric.Image.fromURL(event.target.result, function (img) {
          canvas.add(img);
  });

The canvas is defined here to a specific ID:

            var canvas = new fabric.Canvas(attrs.id, {
                isDrawingMode: true
            });

Depending on the user it will have a different ID. So is important that it gets passed here.

So back to my original question how can I pass the 'event' or variable to the directive?

Let me know if there is anything else i need to add to make it more clear.

0

1 Answer 1

2

You add your variable to scope like this:

scope.setFile = function (element) {
    var reader = new FileReader();

    reader.onload = function (event) {
        $scope.uploadedImage = event.target.result;
    };

    // Reads the image as a data URL.
    reader.readAsDataURL(element.files[0]);
}

then in html

<your-directive var="uploadedImage"></your-directive>

and inside directive you set scope variable

module.directive('yourDirective', function() {
  return {
     scope: {
       var: '='
     },
     ...
  };
});

You can then add watch in directive to check for changes and update the canvas.

Sign up to request clarification or add additional context in comments.

2 Comments

This is a great answer thank you. Out of curiosity how would you add a watch to this so if the variable changes I could reset some code on a function in the directive?
@MaxwellLynn in link function add $scope.$watch('var', function(newValue, oldValue) { });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.