Skip to content

Instantly share code, notes, and snippets.

@thetechnick
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetechnick/ec39f9313f51e8b9dcc4 to your computer and use it in GitHub Desktop.
Save thetechnick/ec39f9313f51e8b9dcc4 to your computer and use it in GitHub Desktop.
AngularJS: extending an controller and bind the scope closures to the right parent
angular.module('app', [])
// Constant to satisfy $injector
.constant('$extend', false)
// Base Controller to extend
.controller('ControllerBase', function($scope, $extend){
'use strict';
var self = $extend ? $extend : this;
// common extended property and function
this.name = 'ControllerBase';
this.logName = function() {
console.info(this.name);
};
// to call scope closures in the right context use .bind(self) (ECMAScript 5)
$scope.logName = function() {
console.info(this.name);
}.bind(self);
// normal $scope closure
$scope.logNameUnbound = function() {
console.info(this.name);
};
})
// Controller which extends the BaseController
.controller('Controller', function($scope, $controller, $extend){
'use strict';
var self = $extend ? $extend : this;
var parent = $controller('ControllerBase', {$scope: $scope, $extend:this});
angular.extend(this, parent);
// scope property
$scope.name = 'test';
// override parent property
this.name = 'Controller';
// common example
this.logName(); // prints "Controller"
parent.logName(); // prints "ControllerBase"
// $scope examples
$scope.logName(); // prints "Controller"
$scope.logNameUnbound(); // prints "test" cause this is now the scope
$scope.logNameUnbound.call(this); //prints "Controller" | use .call(this) or apply(this)
});
@thetechnick
Copy link
Author

I developed this solution while searching for an "angular"-way of extending an existing controller and bind the scope functions to the right controller

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment