I have a code here and I just want to know the better one in getting data from php/mysql. Here are the codes:
1. Using factory
app.factory('todosFactory', function($http) {
var factory = {};
factory.getTodos = function() {
return $http.get('todo-list.php');
};
return factory;
});
app.controller('ListController', function($scope, todosFactory, $http) {
function init() {
todosFactory.getTodos()
.then(function successCallback(data) {
$scope.todos = data;
}, function errorCallback(data) {
console.log(data);
});
}
init();
});
2. GET request directly in the controller
app.controller('ListController', function($scope, $http) {
//Init
function init() {
$http.get('todo-list.php')
.then(function successCallback(data) {
$scope.todos = data;
}, function errorCallback(data) {
console.log(data);
})
}
init();
});
Are there benefits of using one over the other? Thank you.
resolveif you need oneresolveI mentioned....it's a way to have the data returned before the controller and template load, or to get data that the application needs before anything can proceed. Your factory looks fine and you can very easily add to it if you need to but it is the better of the two approaches you mentioned...even if you don't take advantage of that yet.