DRYing controllers with directives and services

The application I'm building has several views, each with its own controller. All of my controllers start out the same and differ in one way:

$scope.a = ...              // same for all controllers
$scope.b = ...              // same for all controllers
$scope.c = function(){...}  // same for all controllers

$scope.d = function(){...}  // is different for each controller

      

Your controllers are said to be thin and factorize them with services. But if I put a, b, c in a service, they are shared across all controllers, where I want each controller to keep its own a, b, c in its own scope. I am not trying to exchange data, just code.

So, I created a directive that refers to the parent scope and declares the shared stuff in its own controller. This solves my problem, but is there a best practice that you could recommend?

+3


source to share


1 answer


If you are defining controller methods as properties of a scope, then you can use a simple mixin method to extend each of the scope objects with generic methods.

Say you are defining an object with reusable methods:

var mixin = {
    a: function() { return this.name; },
    b: function() {},
    c: function() {}
};

      

and then when you need these methods, you just mix them with the current one $scope

:



app.controller('Controller1', function($scope) {

    $scope.name = 'One';

    // Create common methods
    angular.extend($scope, mixin);

    // Define unique method
    $scope.d = function() {};
});

      

Inside the mixin method, a this

separate object will be specified $scope

.

Below is a demonstration of the approach.

Demo: http://plnkr.co/edit/Vc00GsRTi5d6VNcILsva?p=preview

+3


source







All Articles