如何在匿名函数中获取angular服务

How to get angular service in anonymous function

如何正确获取$location服务。下面的代码不起作用,因为最后一行中的 $location 未定义。

(function(location, undefined) {'use strict';
    angular.module('mr.activeLink', [])
    .directive('activeLink', [location, function(location) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {

            }
        };
    }]);
})($location);

应用程序模块:

angular.module('widgetsApp', ['ngRoute', 'ngAnimate',
    'ngResource', 'ngSanitize', 'mr.activeLink']);

Angular 版本 1.2.21

您的代码应该是从依赖项访问 $location 服务。

代码

(function(window, undefined) {
    'use strict';
    angular.module('mr.activeLink', [])
    .directive('activeLink', ['$location', function($location) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
               //$location will be available here
            }
        };
    }]);
})(window);