Calling a service method from a directive template

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 do not understand how to perform two tasks:

  • How do I access the internal path of the image source?
  • How to pass this path to MyService ? (think of a paint wrapper)

Update using 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); } } } }); 
+7
angularjs angularjs-scope angularjs-directive
source share
1 answer
  • You can access the source path by associating it with the area of ​​your controller or using the link method using attributes.

  • You cannot access the Service from the template. You must enter your service in the 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 isolated scope directives here: https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/

+10
source share

All Articles