AngularJS - 将工厂注入指令的链接功能

时间:2014-03-28 18:11:55

标签: angularjs angularjs-directive factory

我有一个简单的代码:

define(['app'], function(app)
{
    app.factory('factoryProvider', function(){
        return {
            name: 'my Name'
        }
    });

    app.directive('myDiv',['factoryProvider', function(factoryProvider) {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'link/to/template.html',
            controller: function($scope) {
            },
            link: function(scope, routeParams, location) {
                console.log(factoryProvider.name);
            }
        };   
    }])
});

我希望能够在myFactory功能中访问link,但我不能!我也尝试了link: function(scope, routeParams, location, factoryProvider),但也没有用。为什么呢?

1 个答案:

答案 0 :(得分:18)

它应该已经在链接功能

中可用
app.factory('factoryProvider', function(){
    return {
        name: 'my Name'
    }
});

app.directive('myDiv',['factoryProvider', function(factoryProvider) {
    return {
        restrict: 'E',
        replace: true,
        template: '<p>{{name}}</p>',
        controller: function($scope) {
        },
        link: function(scope) {
            scope.name=factoryProvider.name;
        }
    };
}]);