Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

How to use built-in services from angularjs directives?


I'm able to get some ID from URL using angularjs built-in $location service. Now, I need to call a service with that ID when the page loads, and then response needs to be rendered in some way.

I'm using ng-init like:

ng-init="uid=$location.path().substring($location.path().lastIndexOf('/') + 1); callToTheService(uid);"

When I execute, this way ng-init is not be able to call the built-in service and that's why I'm getting undefined. What is that I'm missing in AngularJS? I've to configure it in the exact way.


Solution

  • It's best to initialise it in the controller. Simply bind it to scope. Then Inject your service and call a function from it. Here is an example:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $location, YourService) { // injections are important 
      $scope.uid = $location.path().substring($location.path().lastIndexOf('/') + 1);
      $scope.log = function() {
        YourService.callToTheService($scope.uid);
      }
    });
    
    app.service("YourService", function() {
      this.callToTheService = function(uid) {
        console.log("UID: ",uid); // empty in this case
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click="log()">Log UID</button>
    </div>