2016-05-02 73 views
1

我想将One Controller注入服务。AngularJS:如何将Controller注入服务?

我用AngularJs和Laravel和glup-NG-注释。

/* DialogController*/ 
    (function(){ 
     "use strict"; 

     angular.module("music.controllers").controller('DialogController', function($scope, $mdDialog){ 
      $scope.hide = function() { 
       $mdDialog.hide(); 
      }; 
      $scope.cancel = function() { 
       $mdDialog.cancel(); 
      }; 
      $scope.answer = function(answer) { 
       $mdDialog.hide(answer); 
      }; 
     }); 
    })(); 

这是服务

/* Service */ 
(function(){ 
    "use strict"; 

    angular.module("music.services").factory('DialogService', function($mdDialog, DialogController){ 

     return { 
      fromTemplate: function(template, $scope) { 

       var options = { 
        controller: DialogController, 
        templateUrl: template 
       }; 

       if ($scope){ 
        options.scope = $scope.$new(); 
       } 

       return $mdDialog.show(options); 
      }, 

      alert: function(title, content){ 
       $mdDialog.show(
        $mdDialog.alert() 
        .title(title) 
        .content(content) 
        .ok('Ok') 
        ); 
      } 
     }; 
    }); 
})(); 

我有这样的错误

错误:[$注射器:unpr]未知提供商:DialogControllerProvider < - DialogController < - DialogService

+1

工厂/服务可以拥有自己的控制器!您不能将控制器添加/注入到服务/工厂! –

+5

你试图把车放在马前。 – JLRishe

+0

看看这个JS代码,第82和108行,http://codepen.io/kyleledbetter/pen/gbQOaV –

回答

1

服务可以注入到控制器中,但反之亦然。由于AngularJS中的依赖注入支持控制器中的服务注入。

1

控制器应该由$mdDialog服务注入。在名称周围加上引号,以便$mdDialog服务获取字符串而不是引用。

(function(){ 
    "use strict"; 

    angular.module("music.services") 
     .factory('DialogService', function($mdDialog ̶,̶D̶i̶a̶l̶o̶g̶C̶o̶n̶t̶r̶o̶l̶l̶e̶r̶){ 

     return { 
      fromTemplate: function(template, $scope) { 

       var options = { 
        //REPLACE this 
        //controller: DialogController, 
        //WITH this 
        controller: "DialogController", 
        templateUrl: template 
       }; 

       if ($scope){ 
        options.scope = $scope.$new(); 
       } 

       return $mdDialog.show(options); 
      }, 

      alert: function(title, content){ 
       $mdDialog.show(
        $mdDialog.alert() 
        .title(title) 
        .content(content) 
        .ok('Ok') 
        ); 
      } 
     }; 
    }); 
})(); 

在这种情况下options对象传递到服务$mdDialog它执行控制器的注入。

引擎盖下,所述$mdDialog服务使用$controller Service注入指定的控制器。