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

Kou*_*sha 18 factory angularjs angularjs-directive

我有一个简单的代码:

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);
            }
        };   
    }])
});
Run Code Online (Sandbox Code Playgroud)

我希望能够myFactorylink函数内访问,但我不能!我也尝试过link: function(scope, routeParams, location, factoryProvider),但也没用.为什么?

Nic*_*ise 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;
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

  • 好吧,它是为我定义的,但是当我得到返回的参数时,它表示未定义.但是在控制器内部使用时,完全相同的方法返回参数. (3认同)