How to dynamically inject service into a directive in angularjs

My directive is to build a forest table with a delete button. I have a service configured called Post, so when I call the directive, I include the servicename property on the element. How do I dynamically inject my service based on the service name attribute I am including? Or is there a better way to do this?

var lassoDirectives = angular.module('lassoDirectives', []);

lassoDirectives.directive('autoTable', ['parse', function(parse) {
    return {
        restrict: 'AE',
        scope: {
            data: '=',
            modelname: '='
        },
        templateUrl: 'http://local.angular.com/webroot/app/templates/directives/auto-table.html',
        controller: function($scope) {
            console.log(parse);
            $scope.deleteItem = function(id) {
                console.log(id);
                // rocket = modelname.query();
                //console.log(rocket);
            }
            $scope.check = function() {
                parse.get("Posts", 123, function(response) {
                    console.log(response.toString());
                });
            }
        }
    };
}]);

      

+3


source to share


1 answer


I'm not sure if this is the best way to get around this. You should probably have one service that is responsible for all of the data associated with it lassoDirective

, so you can just enter it as usual.

But you can use a provider $injector

like ...



.directive('autoTable', function($injector) {
  return {
    restrict: 'EA',
    scope: {
      servicename: '='
    },
    controller: function(scope) {
       var service = $injector.get(scope.servicename);

       scope.deleteItem = function(Id) {
         del = service.delete({Id: Id});
         items = service.query();
       };
    }
  }
});

      

If you want your service to execute differently depending on the button pressed, it might be better to just pass additional service parameters related to this directive? Not sure if your situation is ignoring this common if N / A.

+4


source







All Articles