Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRYing controllers with directives vs. service

Tags:

angularjs

The app i'm building has multiple views, each with its own controller. All my controllers start in the same way and differ in one methods;

$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

They say keep your controllers thin and factorise them with services. But if I put a, b, c in a service they will be shared among all controllers, wherease I want each controller to keep its own a, b, c in its own scope. I'm not trying to share data, just the code.

So I created a directive that references the parent scope and declares the common stuff in its own controller. It solves my problem but is there a best practice you could recommend?

like image 372
TKrugg Avatar asked Nov 20 '25 06:11

TKrugg


1 Answers

If you define controller methods as scope properties, then you can use simple mixin approach to extend each of the scope objects with common methods.

Say you define an object with reusable methods:

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

and then when you need those methods you simply mix them into current $scope:

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

    $scope.name = 'One';

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

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

Inside mixin methods this will point to individual $scope object.

Below is a demonstration of the approach.

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

like image 140
dfsq Avatar answered Nov 21 '25 20:11

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!