Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling service method from a directive template

Let's say I have a directive:

<component>
   <img ng-src='{{something}}' />
</component>

defined as:

app.directive("component", function() {
    return {
        scope: {},
        restrict: 'E',
        transclude: true,
        template: "<a href='' ng-click='MyService.doThings()' ng-transclude></a>"
    }
});

Despite all my efforts, I fail to understand how to accomplish two tasks:

  1. How do I access the inner image source path?
  2. How can I pass this path to service MyService? (think of a lightbox wrapper)

Update with solution:

app.directive("component", function(LightboxService) {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: "<a href='' ng-click='lb()' ng-transclude></a>",
        link: function (scope, element, attrs) {
            scope.lb = function () {
                var src = $(element).find("img").attr("src");
                LightboxService.show(src);
            }
        }
    }
});
like image 574
Cranio Avatar asked Sep 05 '14 12:09

Cranio


People also ask

Can we call service from a directive in Angular?

You can access the source path either by binding it to your controller scope or from a link method using attributes. You can not access Service from a template. You should inject your service into a controller and define a function in $scope to call from the template.

Which directive we are using to call items from collection?

The ng-repeat directive actually clones HTML elements once for each item in a collection.


1 Answers

  1. You can access the source path either by binding it to your controller scope or from a link method using attributes.

  2. You can not access Service from a template. You should inject your service into a controller and define a function in $scope to call from the template.

Check your directive below:

app.directive("component", function() {
    return {
        scope: {
          ngSrc: "@", //Text Binding
        },
        controller: function($scope, MyService) {
           $scope.doThings = function() {
               MyService.doThings();
           }
        },
        restrict: 'E',
        transclude: true,
        template: "<a href='{{ng-src}}' ng-click='doThings' ng-transclude></a>"
    }
});

You can learn more about directives with isolated scope here: https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/

like image 186
Prasad K - Google Avatar answered Sep 30 '22 13:09

Prasad K - Google