Chuang Fu
Chuang Fu

Reputation: 317

How to use data-binding between controller and templateUrl?

I'm trying to drag an image and drop it on web browser. After drop the image, I get the base64 data in controller and I want to pass the data into the templateUrl. Here is my code:

Controller:

//After drop the image, pass the base64 data to dataUrl
$scope.dataUrl = e.target.result;

Directive:

.directive('crop', [function () {
    return {
        restrict: 'E',
        templateUrl: 'img-token/views/img-crop.html',
        scope: {
            width: '=',
            height: '=',
            dataUrl: '@'
        },
        link: function (scope, elements, attrs) {

            $(elements[0]).children().first().jWindowCrop({
                targetWidth: width,
                targetHeight: height,

                }
            });
        }
    };
}]);

img-crop.html

<img class="crop_me" ng-src="{{dataUrl}}"/>

index.html

<crop width="300" height="300" dataUrl="{{dataUrl}}"></crop>

I want to bind the dataUrl between controller and the templateUrl, is there anything wrong with my code?

Upvotes: 0

Views: 620

Answers (1)

runTarm
runTarm

Reputation: 11547

Ok, I've found why your code does not work.

  1. There is an error in your directive's link function, the width and height aren't defined. They'are in the scope, so the code should be:

    $(elements[0]).children().first().jWindowCrop({
      targetWidth: scope.width,
      targetHeight: scope.height,
    });
    
  2. In directive definition, scope object properties have to be in camelCase dataUrl, but in html attribute it have to be in kebabCase data-url:

    <crop width="300" height="300" data-url="{{dataUrl}}"></crop>
    
  3. This one is the most tricky, for any attribute that begin with data-, angular will strip the prefix out before using it, so the data-url from 2) will become url eventually. The logic is there to allow one to write an angular app that stricly conform to the HTML specification. A workaround is to use data-data-url or just use an another name.

    <crop width="300" height="300" data-data-url="{{dataUrl}}"></crop>
    

Hope this helps!

Example plunker: http://plnkr.co/edit/uo65UVYaF24RBUBeJ5jA?p=preview

Upvotes: 1

Related Questions