注射用NG-控制器所需的依赖 [英] Injecting required dependencies with ng-controller

查看:140
本文介绍了注射用NG-控制器所需的依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ui.router,我们有一个控制器的状态:

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

controller('widget', function($repository, $stateParams){
    $scope.widget = $repository.get($stateParams.id);
})

与注册:

.state('widget',
       controller: 'widget',
       template: '/widgetTemplate.html'

我们已经降临,我们想重用此控制器作为模板的一部分的情况:

We've come upon a case where we like to reuse this controller as part of a template:

<div ng-controller="widget" ng-include="/widgetTemplate.html"></div>

,但似乎没有被注入一个嘲笑$ stateParams对象与正确的ID的简单方法。是这样的:

but there doesn't appear to be an easy way to inject a mocked $stateParams object with the proper ID. Something like:

<div ng-controller="widget" ng-inject="{$stateParams: {id: 1234}}" ng-include="/widgetTemplate.html"></div>

编写增强NG​​控制器自定义指令或重构我们的code利用继承的范围之外,有没有超出现成的方法可以做到这一点?

Outside of writing a custom directive that augments ng-controller or refactoring our code to make use of inherited scopes, are there any out-of-the-box ways to do this?

推荐答案

我不相信有出的现成的方法。 NG-控制器只是使用普通控制器实例,并没有机会注入什么。

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:

<div ng-controller="MainCtrl">
  {{name}}
  <div ng-controller="SecondCtrl" ng-inject="{foo: name, bar: 'bar'}">
  </div>
</div>

和,当然,控制器可以具有这些变量注射

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

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

plunker

这篇关于注射用NG-控制器所需的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆