代码之家  ›  专栏  ›  技术社区  ›  S.Negi

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

  •  0
  • S.Negi  · 技术社区  · 7 年前

    我可以买一些 身份证件 使用angularjs内置从URL $location 服务现在,我需要在页面加载时使用该ID调用服务,然后需要以某种方式呈现响应。

    我使用的是ng init,比如:

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

    当我执行时,这样ng init就无法调用内置服务,这就是为什么我没有定义。我在AngularJS中遗漏了什么?我必须以精确的方式配置它。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Aleksey Solovey    7 年前

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

    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>