Angularjs -装饰控制器



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

我已经把它配置成在Angular 1.2中工作。X,但有一些突破性的变化从1.3。X之后就会破坏代码。现在得到的错误是"controller is not a function"

下面是装饰器的代码:
angular.module('myApp', ['ng'], function($provide) {
    $provide.decorator('$controller', function($delegate) {
        return function(constructor, locals) {
                //Custom behaviour code
                return $delegate(constructor, locals);
            }
        })
    });

1.2角。x - http://jsfiddle.net/3v17w364/2/(工作)
1.4角。x - http://jsfiddle.net/tncquyxo/2/(破碎)

x模块有decorator方法,不再需要$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);
    };
});

回答我自己的问题

必须深入研究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/

最新更新