Thursday, 24 September 2015

angularjs controller inherit and override

Inherit is very easy, as i mentioned in :

In this post i will show how to override parent functions

var app = angular.module('angularjs-starter', []);

app.controller('ParentCtrl ', function($scope) {
  // I'm the sibling, but want to act as parent

app.controller('ChildCtrl', function($scope, $controller) {
     var inst = $controller('ParentCtrl', {$scope: $scope}); //This works

    // Perform override a property and function. (but see blow, very important !!) 
    inst.baz = + " extended";

    // override property or function of the scope
    $scope.child = inst;

In your parent controller, you must define your function and properties like that: ($scope.xx will always overridable)

app.controller('ParentCtrl ', function($scope) {
        var currentController = this; 
        currentController.username = "peter";        currentController.showData = function(data) {

        function loadApps(device) {

"showData" and "username" are overridable properties and functions. However "loadApps" is not a overridable function.

note :

"showData" and "username" are public properties and functions.

"loadApps" is inner anonymous function (you can treat it as a private function if you use java).

You may want to override functions when you are doing unittest.

No comments:

Post a comment