Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - Decorate Controllers

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 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".

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

Angular 1.2.x - http://jsfiddle.net/3v17w364/2/ (Working)
Angular 1.4.x - http://jsfiddle.net/tncquyxo/2/ (Broken)

like image 915
Angad Avatar asked Sep 07 '15 16:09

Angad


1 Answers

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

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);
    };
});
like image 132
Estus Flask Avatar answered Nov 11 '22 14:11

Estus Flask