javascript - Reuse AngularJS controller logic -
this code of 1 controller application, in 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 page, permission page, create controller 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 can see, different url. how can reuse logic controller another?
that services for.
so instead of:
$http.get('/permission/getpermissions').success(function (data) {     $scope.data= data; });   you'd call 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 like:
this.search = function () {     searchservice.search().then(function (data) {         $scope.data = data;     }); }   etc...
generally, server calls should in services anyway, there's great opportunity improve code and learn how right.
Comments
Post a Comment