如何使用 angularjs 指令中的内置服务?

How to use built-in services from angularjs directives?

我可以使用 angularjs 内置 $location 服务从 URL 获得一些 ID。现在,我需要在页面加载时调用具有该 ID 的服务,然后需要以某种方式呈现响应。

我正在像这样使用 ng-init:

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

当我执行时,这种方式 ng-init 无法调用内置服务,这就是我未定义的原因。我在 AngularJS 中缺少什么?我必须以准确的方式配置它。

最好在控制器中初始化。只需将其绑定到范围。然后注入您的服务并从中调用一个函数。这是一个例子:

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>