1

This is the code of one controller from my application, in the User page.

app.controller('UserCtrl', ['$scope', '$http', function ($scope, $http) {

$http.get('/Users/GetUsers').success(function (data) {
    $scope.data = data;
});

this.search = function () {
    $http.post('/Users/SearchUser', $scope.search).success(function (data) {
        $scope.data = data;
    });
}

this.delete = function() {....}
}]);

On another page, the Permission page, I create a controller with the same logic

app.controller('PerCtrl', ['$scope', '$http', function ($scope, $http) {

$http.get('/Permission/GetPermissions').success(function (data) {
    $scope.data= data;
});

this.search = function () {
    $http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
        $scope.data = data;
    });
}

this.delete = function() {....}
}]);

As you can see, the only different is the URL. How can I reuse the logic from a controller to another?

1 Answer 1

1

That is exactly what services are for.

So instead of:

$http.get('/Permission/GetPermissions').success(function (data) {
    $scope.data= data;
});

You'd call something like:

permissionsService.get().then(function (data) {
    $scope.data= data;
});

And:

this.search = function () {
    $http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
        $scope.data = data;
    });
}

Replaced with something like:

this.search = function () {
    searchService.search().then(function (data) {
        $scope.data = data;
    });
}

etc...

Generally, all server calls should be in services anyway, so there's a great opportunity to improve your code and learn how to do it right.

Sign up to request clarification or add additional context in comments.

2 Comments

I know about the service, but if I use the service, I still have to declare the "search, delete" in each controller. What I want is create a parent controller, other controller inherit from it, and I only need to configure the url for Get and Search, Delete .... or something like that.
Well then, create a service that does all that for you... It's really a job for a service rather than a controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.