How can I write more clear this code?


#1

Hello guys. I try to develop an app and i need help about writing clear code. I’m new on this and I want to do good stuff.

In app I have few section which have same process, in controller part I don’t want to write this code again and again. I found few topic about this, somebody says you should use service another says you should use factory. I even don’T understand what is the basic difference between them and also didn’t implement it into my code as well. Here is the my two controller code which I don’t want to duplicate.

.controller('CategoriesBorrowFromCtrl', function($scope, $location, $state, Books){
  var absUrl = $location.search();
  var booksinfo = [];
  Books.getinf(String(absUrl.info)).then(function(data){
    for (var i = 0; i < data.length; i++) {
      Books.get(data[i]).then(function(response){
        booksinfo.push(response);
      });
    }
    $scope.getinfos=booksinfo;
  })
})

.controller('CategoriesLendToCtrl', function($scope, $location, $state, Books){
  var absUrl = $location.search();
  var booksinfo = [];
  Books.getinf(String(absUrl.info)).then(function(data){
    for (var i = 0; i < data.length; i++) {
      Books.get(data[i]).then(function(response){
        booksinfo.push(response);
      });
    }
    $scope.getinfos=booksinfo;
  })
})

Here is the my factory code:

.factory('Books', function($http, $q, $ionicPopup, $state) {
 
    return {
        get: function(customerBookId) {
            var defer = $q.defer();
            $http.get('http://localhost/webservice/server/?a=detail&id='+customerBookId).success(function(response){
                defer.resolve(response);
            });
            return defer.promise;
        },
        getinf: function(userscase){
            var defer= $q.defer();
            var id=[];
            $http.get('http://localhost/webservice/server/?a=getinfo&info='+userscase).success(function(response){
               for (var i = 0; i < response.length; i++) {
                    id.push(response[i].id);
               }
               defer.resolve(id)
            });
            return defer.promise;
        }
    }
});


#2

can become

$scope.getinfos = someFunctionSomewhere($location.search());

You just have to decide where you want to put this function.

They are almost the same in Ionic 1 / AngularJS.


#3

Okay thank you :slight_smile: You mean service,factory or value almost the same and doesn’t matter where i put it.