如何在匿名函数中获得角度服务

时间:2015-02-02 14:56:39

标签: angularjs angularjs-directive

如何正确获取$ 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

1 个答案:

答案 0 :(得分:0)

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

<强> CODE

(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);