Vince Verhoeven
Vince Verhoeven

Reputation: 1773

angularJS share methods between directives

how do I share a method between two directives? When I try it now the console says scope.triggerInput(); is undefined; If I replace the scope.triggerinput with just a string it works. So I guess I do it somewhere wrong in the attribute.

app.directive('myImage', function () {
    return{
         restrict: 'A',
         template: ' <img ng-src="images/needed/noPhoto.png"class="hover">',
         link: function (scope, element, attr) {
              element.bind('click', function () {
                   scope.triggerInput();
              });
          }
     };
});   

app.directive('myFileInput', function (httpPostFactory) {
        return{
            restrict: 'A',
            scope: {
                triggerInput: '='
            },
            link: function (scope, element, attr) {
                scope.triggerInput = function () {
                    console.log('triggerInput');
                    element[0].click();
                };
            }
        };
    });

html

<div data-my-image></div>
<input data-my-file-input type="file" name="file" triggerInput='triggerInput()'>

Upvotes: 3

Views: 1112

Answers (1)

superczan
superczan

Reputation: 306

Very good question! If I understand your situation correctly, Angular Service is what you need to use for situations like these.

app.service('clickResponder',function(){
   var srvc={};
   srvc.triggerInput=function(){
       // Do your stuff here. 
   }
  return srvc;

}

Now, to use this service, its very simple just inject it on your directive like below:

app.directive('myImage', function (clickResponder) {
return{
     restrict: 'A',
     template: ' <img ng-src="images/needed/noPhoto.png"class="hover">',
     link: function (scope, element, attr) {
          element.bind('click', function () {
               clickResponder.triggerInput();
          });
      }
 };
});   

Thats all you need to do. Hope this helps you in some way!

Upvotes: 3

Related Questions