2016-05-02 89 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注入指定的控制器。