6

我正在尝试为我的控制器设置一个装饰器。我的目的是在我的应用程序中的所有控制器中引入一些常见的行为。

我已将它配置为在 Angular 1.2.x 中工作,但从 1.3.x 开始有一些破坏性的更改会破坏代码。现在得到的错误是“控制器不是函数”

下面是装饰器的代码:

angular.module('myApp', ['ng'], function($provide) {
    $provide.decorator('$controller', function($delegate) {

        return function(constructor, locals) {

                //Custom behaviour code

                return $delegate(constructor, locals);
            }
        })
    });

Angular 1.2.x - http://jsfiddle.net/3v17w364/2/ (工作)
Angular 1.4.x - http://jsfiddle.net/tncquyxo/2/ (坏了)

4

2 回答 2

10

在 Angular 1.4.x 模块中有装饰器方法,$provide.decorator不再需要。

对于猴子修补 API,总是最好使用arguments而不是显式枚举它们,它破坏的可能性要小得多。

angular.module('myApp', ['ng']).decorator('$controller', function ($delegate) {
    return function (constructor, locals) {
        var controller = $delegate.apply(null, arguments);

        return angular.extend(function () {
            locals.$scope.common = ...;
            return controller();
        }, controller);
    };
});
于 2015-09-07T20:17:52.203 回答
2

回答我自己的问题。

不得不深入研究 Angular 源代码以弄清楚发生了什么。

$controller 实例是使用以下代码创建的。修复在于参数“稍后”。这需要设置为true

    return function(expression, locals, later, ident) {
      // PRIVATE API:
      //   param `later` --- indicates that the controller's constructor is invoked at a later time.
      //                     If true, $controller will allocate the object with the correct
      //                     prototype chain, but will not invoke the controller until a returned
      //                     callback is invoked.

以上取自:https ://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js

更新的提供者代码:

angular.module('myApp', ['ng'], function($provide) {
    $provide.decorator('$controller', function($delegate) {

 return function(constructor, locals) {

            //Custom behaviour code

            return $delegate(constructor, locals, true);
        }
    })
});

更新小提琴:http: //jsfiddle.net/v3067u98/1/

于 2015-09-07T16:43:34.047 回答