如何将服务注入链接函数包含指令



我正在尝试将服务注入到以下指令中,该指令使用链接函数而不是控制器。

(function() {
angular
.module("myApp")
.directive('myDirective',['$scope','myService','myData',function($scope,myService,myData) {
return {
     restrict'AE',
     replace:'true',
     templateUrl :'/myApp/directive/my-directive',
     scope: {
      userId: "@"
      }
    },
    link:function(scope,elem,attr)
      {
         //Code for link function goes here ...
          scope.myUsersArray [];
          scope.getUserDetails = function()
              {
                //code for getUserdetails goes here...
              }
       }
    }]);
    })();

当我运行此代码时,我收到类似 [$injector:unpr] Unkown 提供程序 <_ $scope错误的异常。如果我删除注入的服务,则不会收到任何错误。错误抛出角度.js文件,所以我没有任何线索可以修复它:(

您有几个语法问题。 您的代码应如下所示:

  .directive('myDirective', ['$scope', 'myService', 'myData', function($scope, myService, myData) {
    return {
      restrict: 'AE',
      replace: 'true',
      templateUrl: '/myApp/directive/my-directive',
      scope: {
        userId: "@"
      },
      link: function(scope, elem, attr) {
        //Code for link function goes here ...
        scope.myUsersArray = [];
        scope.getUserDetails = function() {
          //code for getUserdetails goes here...
        };
      }
    };
  }]);

您可能会遇到更多问题,因为对于为什么要注入$scope,myService和myData并不明显

最新更新