Angularjs - 装饰控制器 [英] Angularjs - Decorate Controllers

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

问题描述

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

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);
    };
});

这篇关于Angularjs - 装饰控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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