Angularjs - 将服务动态传递给指令

Angularjs - Passing a service to a directive dynamically

我必须在 angularjs 1.2

中优化应用程序

这是代码 jade 文件,我在其中将服务动态传递给我的指令 (creaDatos.jade)

div(datos-u, service="userDataSrv") // The div has associated a directive to which has service is dynamically passed

这是代码指令(datosU.js)

(appModule.lazy || appModule)
    .directive('datosU', [ function() {

        // Runs during compile
        return {
            restrict: 'A',
            scope: {
                service: '='
            },
            templateUrl: 'commons/html/user.html',
            controller: 'userCtrl'
        };
    }]);

这是代码控制器(userCtrl.js)

(appModule.lazy || appModule)
.controller('userCtrl', ['$scope', '$injector',
    function($scope, $injector) {

        var srv = $injector.get($scope.service); /* The variable "srv" should have the value "userDataSrv" but his value is "undefined", The value of "$scope.service" is "undefined" */

    }]);

这是浏览器控制台中的错误:

Error: [$injector:unpr] Unknown provider: undefinedProvider <- 
http://errors.angularjs.org/1.2.16/$injector/unpr?p0=undefinedProvider%20%3C-%20

我不知道我做错了什么,你能帮帮我吗?

不要对 service (=) 使用双向绑定,而是使用字符串绑定 (@)。

因此,将您的指令更改为:

(appModule.lazy || appModule)
    .directive('datosU', [ function() {

        // Runs during compile
        return {
            restrict: 'A',
            scope: {
                service: '@'
            },
            templateUrl: 'commons/html/user.html',
            controller: 'userCtrl'
        };
    }]);