使用controllerAs语法&扩展Angular控制器原型继承 [英] Extend Angular controllers using controllerAs syntax & prototypical inheritance

查看:31
本文介绍了使用controllerAs语法&扩展Angular控制器原型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用conrollerAs语法扩展控制器.我的父控制器和子控制器未在同一范围内定义,因此我将父控制器( BaseController )放在服务中:

I'm trying to extend controllers using conrollerAs syntax. My parent and child controllers are not defined in the same scope, so I put the parent controller (BaseController) in a service:

angular.module('myApp').factory('BaseController', function() {
  var BaseController = function(fooService, barService) {
    // base controller constructor logic
  }

  BaseController.prototype = {
    // base controller methods
  }

  return BaseController;
});

然后像这样使用它:

var ChildController = function(BaseController, fooService, barService) {
  BaseController.apply(this, [fooService, barService]);
}

var BaseController = angular.injector(['myApp']).get('BaseController');

ChildController.prototype = Object.create(angular.extend(BaseController.prototype, {
  fooMethod: function() {
    // do stuff
  }
}));

angular.module('myApp').controller('ChildController', ChildController);

我在ui路由器状态下使用 ChildController .状态模板无法加载,并且在控制台中出现错误:

I use ChildController in a ui router state. The state template doesn't load, and I get an error in the console:

未定义页面控制器的资源< div class ="ng-scope" ui-view ="foo-view">

有什么想法吗?

推荐答案

angular.injector 创建一个新的喷射器实例(如果听起来更好,则为应用程序实例),不应在在Angular应用中进行生产.即

angular.injector creates a new injector instance (which is application instance, if it sounds better) and shouldn't be used in production within Angular app. I.e.

angular.injector(['myApp']).get('BaseController') !== angular.injector(['myApp']).get('BaseController');

当您仍然能够注册控制器时,您需要动手使用 BaseController 依赖项,唯一的执行位置是配置阶段,

You need to put your hands on BaseController dependency when you're still able to register controllers, and the only place for doing this is config phase,

angular.module('myApp').config(function($controllerProvider, BaseController) {
  ...
  $controllerProvider.register('ChildController', ...)
});

这要求 BaseController 必须是 constant ,而不是 factory ,并且可能会限制您要使用它执行的操作.听起来不太有趣,不是吗?

This requires BaseController to be constant, not factory, and possibly limits the things you would like to do with it. Sounds less funny, doesn't it?

所以在这里要做的更好的事情就是

So a better thing to do here is just

var ChildController = function(BaseController, fooService, barService) {
  angular.extend(this, BaseController.prototype, { ... });
  BaseController.apply(this, [fooService, barService]);
}

angular.module('myApp').controller('ChildController', ChildController);

由于上述原因,Angular DI不适合OOP JS,仍然需要其他模块化解决方案进行补充.

Angular DI isn't suited well for OOP JS for the reasons shown above and still needs to be supplemented with other modular solutions.

这篇关于使用controllerAs语法&amp;扩展Angular控制器原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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