2016-05-02 17 views
1

サービスにOne Controllerを注入したい。AngularJS:コントローラをサービスに挿入する方法は?

私はAngularJsとLaravelとglup-ng-annotateを使用します。

/* 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を使用します。

関連する問題