Mihai Gota Mihai Gota - 6 months ago 18
jQuery Question

How to access a variable from a angular directive?

This directive is assigned to an image and it's using an jQuery plugin called Cropper. How can I get in HTML or in another angular controller the dynamic variable width and height of the element:

e.width
or
e.height


.directive( "imgcrop", [function ($scope, $controller) {
return {
restrict: "A",
scope: {
proposal : "="
},
transclude: true,
replace: true,
link : function ( $scope, $el, $attr ) {
$attr.$observe( "src", function ( src ) {
jQuery( '#cropImage' ).cropper('destroy');
jQuery( '#cropImage' ).cropper( {
viewMode : 0,
zoomable : false,
preview: ".extra-preview",
dragMode : 'crop',
guides : true,
highlight : true,
cropBoxMovable : true,
cropBoxResizable: true,
crop : function ( e ) {
// Output the result data for cropping image.
console.log( e.width );
console.log( e.height );
}
} );

} );
}
}
} ] );

Answer

Setup a scope binding which you can use to pass the width and height back to the controller.

    .directive( "imgcrop", [function ($scope, $controller) {
          return {
              restrict: "A",
              scope: {
                proposal : "="
                , croppedWidth: '='
                , croppedHeight: '='
              },
              transclude: true,
              replace: true,
              link    : function ( $scope, $el, $attr ) {
                  $attr.$observe( "src", function ( src ) {
                      jQuery( '#cropImage' ).cropper('destroy');
                      jQuery( '#cropImage' ).cropper( {
                          viewMode        : 0,
                          zoomable        : false,
                          preview: ".extra-preview",
                          dragMode        : 'crop',
                          guides          : true,
                          highlight       : true,
                          cropBoxMovable  : true,
                          cropBoxResizable: true,
                          crop            : function ( e ) {
                              // Output the result data for cropping image.
                              $scope.croppedWidth = e.width;
                              $scope.croppedHeight = e.height;
                          }
                      } );
                  } );
              }
          }
    } ] );

Then on your image:

<img imgcrop croppedWidth="vm.width" croppedHeight="vm.height">
Comments