Saturday, 28 November 2015

Angular Inherence

Writing a code to application like my could cross a point of readability and flexibility if all functions supporting one model of data I put to one controller. I decided to change it. I have to exclude my model to other module's fiction. Some of common methods for a few controllers can be excluded to other parent controller and inherit it.


My idea is to use factory to have in controllers a shared model instance and parent controller to support the most common operations and extend it in children classes.
Ex. var App = angular.module('App', []);
Below is shared model with public api.
App.factory('SharedModel', function () {
    var model = { /* some definition of object */   };
    // public API
    return {
        getValue: function() {
           return model.value;
        },
        updateValue: function(value) {
           model.value = value;
        }
    };
});
Parent controller
App.controller("ParentCtrl", function($scope, MyParentService,SharedModel) {

    $scope.parentMethod = function(){
        SharedModel.updateValue({'par1' : 'myValue'});
        console.info('do something');
    }
});
Child controller. Angularjs support inheritance of controllers.
App.controller("DefaultCtrl", function($scope, $controller, SharedModel, MyService) {
    $controller('ParentCtrl', {$scope: $scope});
  
    $scope.setVal = function(text){
        MyService.setText(text);
        sharedModel.updateValue(text);
    };
    $scope.getVal = function(){
        return SharedModel.getValue();
    };
  
    $scope.getServiceVal = function(){
        return MyService.myBase();
    };
    $scope.getMyServiceVal = function(){
        return MyService.myService();
    };
  
});
Top service body.
function MyBaseService($http) {
    this.text = "MyBaseServiceText";
    this.loaded = false;
    this.myBase = function(){
        console.log("MyBaseService.myBase");
        if(!this.loaded){
            $http({
                method: 'GET',
                url: 'http://localhost/',
            });
            this.loaded = true;
        }
        return this.text;
    }
};
Medium service body.

function MyParentService($http) {
    MyBaseService.call(this,$http);
    this.getSomething = function(){
        return 'something';
    }
};
Child service body used in controller.

function MyService($http) {
    MyBaseService.call(this,$http);
    this.myService = function(){
        console.log("called my service" + this.text);
        $http({
            method: 'GET',
            url: 'http://localhost/',
        });
    }
};
Registration of service body in Angularjs's context.
App.service("MyBaseService", MyBaseService);
App.service("MyParentService", MyParentService);
App.service("MyService", MyService);
It's quite easy..... isn't it ?

No comments:

Post a Comment