Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass a variable from a controller to a directive? Angular.JS

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.

like image 538
MaxwellLynn Avatar asked Apr 08 '26 06:04

MaxwellLynn


1 Answers

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.

like image 197
jcubic Avatar answered Apr 10 '26 19:04

jcubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!