angularjs share data config between controllers

Consider the method described by this post: Extending AngularJS Controllers Using the Mixin Pattern

Instead of copying your methods out of a service, create a base controller that contains those methods, and then call extend on your derived controllers to mix them in. The example from the post:

function AnimalController($scope, vocalization, color, runSpeed) {

    var _this = this;

    // Mixin instance properties.
    this.vocalization = vocalization;
    this.runSpeed = runSpeed;

    // Mixin instance methods.
    this.vocalize = function () {
        console.log(this.vocalization);
    };

    // Mixin scope properties.
    $scope.color = color;

    // Mixin scope methods.
    $scope.run = function(){
        console.log("run speed: " + _this.runSpeed );
    };
}

Now we can mixin AnimalController into DogController:

function DogController($scope) {

    var _this = this;

    // Mixin Animal functionality into Dog.
    angular.extend(this, new AnimalController($scope, 'BARK BARK!', 'solid black', '35mph'));

    $scope.bark = function () {
        _this.vocalize(); // inherited from mixin.
    }
}

And then use DogController in our template:

<section ng-controller="DogController">
    <p>Dog</p>

    <!-- Scope property mixin, displays: 'color: solid black' -->
    <p ng-bind-template="color: {{ color }}"></p>

    <!-- Calls an instance method mixin, outputs: 'BARK BARK!' -->
    <button class="btn" ng-click="bark()">Bark Dog</button>

    <!-- Scope method mixin, outputs: 'run speed: 35mph' -->
    <button class="btn" ng-click="run()">Run Dog</button>
</section>

The controllers in this example are all in the global space and are included in the markup as follows.

<script type="text/javascript" src="https://stackoverflow.com/questions/21427027/lib/jquery.js"></script>
<script type="text/javascript" src="lib/angular.js"></script>
<script type="text/javascript" src="app/controllers/animal-controller.js"></script>
<script type="text/javascript" src="app/controllers/dog-controller.js"></script>
<script type="text/javascript" src="app/controllers/cat-controller.js"></script>
<script type="text/javascript" src="app/app.js"></script>

I haven’t tested it, but I don’t see why the following wouldn’t work:

var myApp = angular.module('myApp', [])

.controller('AnimalController', ['$scope', 'vocalization', 'color', 'runSpeed', function ($scope, vocalization, color, runSpeed) { /* controller code here */}]);

.controller('DogController', ['$scope', '$controller', function($scope, $controller) {
    var _this = this;

    // Mixin Animal functionality into Dog.
    angular.extend(this, $controller('AnimalController', {
         $scope: scope,
         vocalization: 'BARK BARK!', 
         color: 'solid black', 
         runSpeed:'35mph' 
    }));

    $scope.bark = function () {
        _this.vocalize(); // inherited from mixin.
    }
}]);

see: docs for $controller service

Leave a Comment