angularjs - DRYing controllers with directives vs. service -
the app i'm building has multiple views, each own controller. controllers start in same way , differ in 1 methods;
$scope.a = ... // same controllers $scope.b = ... // same controllers $scope.c = function(){...} // same controllers $scope.d = function(){...} // different each controller
they keep controllers thin , factorise them services. if put a, b, c in service shared among controllers, wherease want each controller keep own a, b, c in own scope. i'm not trying share data, code.
so created directive references parent scope , declares common stuff in own controller. solves problem there best practice recommend?
if define controller methods scope properties, can use simple mixin approach extend each of scope objects common methods.
say define object reusable methods:
var mixin = { a: function() { return this.name; }, b: function() {}, c: function() {} };
and when need methods mix them 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
point individual $scope
object.
below demonstration of approach.
Comments
Post a Comment