Last active
August 29, 2015 14:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I developed this solution while searching for an "angular"-way of extending an existing controller and bind the scope functions to the right controller