Friday, February 20, 2015

AngularJS Reusing by overriding and extending.

I always try to write reusable code and I found in Angular JS how to do it
Maybe this is not elegant or recommend but it works .. !

This is my simple example:

The controller calls a factory that receives the $scope as parameter.
The factory adds to the $scope values and functions that can be used directly in the view or by the controller:
sets: value1 and value2 default value.
defines; action1, action3 and action4 functions
action4  checks if exists onAction4 that extends its default behavior.

Then in the controller:
action2 is defined
action3 is redefined (overridden)
onAction4 is defined to extend action4 defaults behavior.


Note in this implementation is not necessary to define
 $scope.action2 = function(){commonBehavior.action2();} because action2 was added to the current scope by addToScope


You can see it working here in Plunker


var app = angular.module('app', ['commonBehavior']);

angular.module('commonBehavior', [])
.factory('commonBehavior', function () {
    var ext = {};
    ext.addToScope = function ($scope) {
        $scope.value1 = "Common Behavior Value 1";
        $scope.value2 = "Common Behavior Value 2";

        $scope.action1 = function () {
            $scope.value1 = "action1";
        }
        $scope.action3 = function () {
            $scope.value1 = "action3 commonBehavior";
        }

        $scope.action4 = function () {
            $scope.value1 = "action4 commonBehavior";

            if ($scope.onAction4 != undefined) //  if it is defined in the controller execute it.
                $scope.onAction4();
        }

    }
    return ext;
});

app.controller("myCtrl", ['$scope', 'commonBehavior', function ($scope, commonBehavior) {
    commonBehavior.addToScope($scope); // sets the scope
    $scope.value2 = "overridden Value 2"; //override default value

    $scope.action2 = function () {
        $scope.value1 = "action2";
    }

    $scope.action3 = function () { //function overriden
        $scope.value1 = "action3 overridden";
    }
    $scope.onAction4 = function () { //susbcribed to the event
        $scope.value2 = "onAction4";
    }
}
]);

2 comments:

  1. Extremely useful information which you have shared here about Angular app development. This is a great way to enhance knowledge for us, and also beneficial for us. Thank you for sharing a post like this. Best Angular Development Agency in USA

    ReplyDelete
  2. BigSpinCasino manages to strike the right stability between a colourful design and being very practical. This isn’t the easiest factor to do within the sea of overly cartoonish or plain too bland on-line casinos. The BigSpinCasino signup offer features a 200% 1xbet match bonus in your first deposit up to as} $1,000. You solely have to wager the bonus 30 times earlier than getting your hands on it.

    ReplyDelete