Angularjs - 装饰控制器控制器、Angularjs

由网友(Self-pity 妄自菲薄)分享简介:我想建立一个装饰我的控制器。我的目的是介绍我的应用程序在所有控制器的一些常见的行为。 I am trying to set up a decorator for my controllers. My intention is to introduce some common behaviour across all...

我想建立一个装饰我的控制器。我的目的是介绍我的应用程序在所有控制器的一些常见的行为。

I am trying to set up a decorator for my controllers. My intention is to introduce some common behaviour across all the controllers in my app.

我有麻烦找到设置此功能的正确方法。

I am having troubles finding the right way of setting this up.

我把它配置在角1.2.x的工作,但也有从1.3.x中一些重大的变化开始被打破了code。该误区一现在得到的控制器是不是一个函数

I have it configured to work in Angular 1.2.x, but there are some breaking changes from 1.3.x onwards that is breaking the code. The error one now gets is "controller is not a function".

下面是code的装饰:

Below is the code for the decorator:

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/ (断)

推荐答案

在角1.4.x的模块具有的装饰方法, $ provide.decorator 不再需要。

In Angular 1.4.x modules have decorator method, $provide.decorator is no longer needed.

有关猴子修补的API它总是preferable使用参数,而不是明确地列举它们,这将打破机会少得多。

For monkey-patching APIs it is always preferable to use arguments instead of enumerating them explicitly, the chance that it will break is much lesser.

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);
    };
});
阅读全文

相关推荐

最新文章