Injecting required dependencies with ng-controller

后端 未结 3 1458
南旧
南旧 2020-12-17 03:14

Using ui.router, we have a controller for a state:

controller(\'widget\', function($repository, $stateParams){
    $scope.widget = $repository.get($statePara         


        
3条回答
  •  一生所求
    2020-12-17 03:56

    I don't believe there is an out-of-the-box way. ng-controller just uses normal controller instantiation, and there is no opportunity to inject anything.

    But this is an interesting "feature", which can be built, actually, relatively simply with a custom directive.

    Here's an illustrative example (disclaimer: it is definitely not tested under obscure scenarios):

    .directive("ngInject", function($parse, $interpolate, $controller, $compile) {
      return {
        terminal: true,
        transclude: true,
        priority: 510,
        link: function(scope, element, attrs, ctrls, transclude) {
    
          if (!attrs.ngController) {
            element.removeAttr("ng-inject");
            $compile(element)(scope);
            return;
          }
    
          var controllerName = attrs.ngController;
    
          var newScope = scope.$new(false);
    
          var locals = $parse(attrs.ngInject)(scope);
          locals.$scope = newScope;
    
          var controller = $controller(controllerName, locals);
    
          element.data("ngControllerController", controller);
    
          element.removeAttr("ng-inject").removeAttr("ng-controller");
          $compile(element)(newScope);
          transclude(newScope, function(clone){
            element.append(clone);
          });
          // restore to hide tracks
          element.attr("ng-controller", controllerName); 
        }
      };
    });
    

    The usage is as you described it:

    {{name}}

    And, of course, the controller can have these variables injected:

    .controller("SecondCtrl", function($scope, foo, bar){
    });
    

    plunker

提交回复
热议问题