AngularJS Extend Controller

I use angular to create a large application, and I have some common methods for controllers that really do this, but is there a better way to do this?

app.controller('baseController', function($scope, $controller, appFactory) {
    var $scope.foo = function() {
        // Do something
    }
});


app.controller('childController', function($scope, $controller, appFactory) {

    // Here i extend or something like, the base controller

    $controller('baseController', {$scope: $scope});

    var $scope.bar = function() {
        // Do a lot of things an then call foo
        $scope.foo();
    }
}):

I do this because for this method you must have $ scope of my controller.

+4
source share
2 answers

, . , DRY, / Factory/Providers. @Clever, $scope.foo = function() { MyFactory.calculateFoo(); } X , . , .

Misko Google AngularJS . , , :

$injector.invoke(MyBaseController, this, { $scope: $scope, alertService: alertService });

, , CRUD , / $scope. , , .. CRUD?

+3

, KayakDave, Angular . , "" , , , . , , /Factory/. :

app.Factory('MyFactory', function() {
    return {
        calculateFoo: function() { 
          // stuff 
        }
    };

});

app.controller('FirstCtrl', function($scope, $controller, MyFactory) {
    var $scope.foo = function() {
        MyFactory.calculateFoo();
    }
});


app.controller('SecondCtrl', function($scope, $controller, MyFactory) {

    var $scope.bar = function() {
        MyFactory.calculateFoo();
    }
}):
+1

All Articles