Raz Buchnik
Raz Buchnik

Reputation: 8411

AngularJS is it possible to use service that was injected via html scope directly?

I have this directive:

app.directive("saveButton", ($rootScope, ConfirmationModal) => {
  return {
    templateUrl: "/structure/header/components/save-button/save-button.html",
    scope: true,
    link: function($scope, element, attrs) {

      $scope.ConfirmationModal = ConfirmationModal;

    }
  }
});

And I have this HTML template of the directive:

<button ng-click="ConfirmationModal.default()">
  Click here
</button>

The above is working, but notice that in the directive JS file I have attached the service to the scope: $scope.ConfirmationModal = ConfirmationModal;.

My question is, is this possible to make the service available without the attachment?

Upvotes: 0

Views: 153

Answers (1)

Skomantas Čepulis
Skomantas Čepulis

Reputation: 31

first of all, i think you're not really supposed to use services directly. I think angular way would be more like to use services inside controller/component.

Short answer would be No. It's not possible to make the service available without the attachment. But let's assume you need to use it directly, so yes, you need to bind it to scope. Like you did here already.

But, if you don't really want to bind it here, you cant bind it in parent controller/component. By default directive is inheriting parent $scope, so you can bind it once in parent, all inside this parent (controller or component) 'saveButton' directives will have it also.

angular.module('docsIsolateScopeDirective', [])
 .controller('ParentController', ['$scope','ConfirmationModal' function($scope, ConfirmationModal) {
 $scope.ConfirmationModal = ConfirmationModal;
}])
.directive('myCustomer', function() {
  return {
    templateUrl: '/structure/header/components/save-button/save-button.html'
  };
});

Additionally, you can pass specific scope variable to directive like this:

scope: {
  ConfirmationModal: '=ConfirmationModal'
},

And you pass it from the parent

save-button(confirmation-modal="$ctrl.confirmationModal")

So all in all, i would recommend to use component over directive here, since is 'statefull', and it would be far more convenient. Then use Service inside controller of the component. And use something like submit() function and call service inside controller, and bind to scope only this submit.

Hope it helps, Cheers.

References: https://docs.angularjs.org/guide/directive

Upvotes: 1

Related Questions