Thursday, 24 September 2015

angularjs controller inherit and override


Inherit is very easy, as i mentioned in :http://baiduhix.blogspot.co.uk/2015/09/angularjs-controller-inherit.html

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 = inst.foo + " 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) {
            console.log("showData");
        };

        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