Comparing Two Approaches:
Approach A.
- Creating app module
- Using a service to store model data
- Implementing a controller to retrieve data from the service
File 1: Users.js
:
angular.module('users', []);
File 2: userService.js
:
angular.module('users').service('userService', ['$q', UserService]);
function UserService($q) {
var users = [
{
name: 'Bob Smith',
age: 26,
address: 'London',
},
{
name: 'John Simpson',
age: 41,
address: 'New York',
},
{
name: 'Maria West',
age: 36,
address: 'Chicago',
}
];
// Promise-based API
return {
loadAllUsers : function() {
// Simulate async nature of real remote calls
return $q.when(users);
}
};
}
})();
File 3: UserController.js
:
angular.module('users').controller('UserController', ['$scope', function($scope) {
$scope.selected = null;
$scope.users = [];
$scope.selectUser = selectUser;
$scope.toggleList = toggleUsersList;
$scope.makeContact = makeContact;
userService
.loadAllUsers()
.then( function( users ) {
$scope.users = [].concat(users);
$scope.selected = users[0];
});
}]);
Approach B:
- Creating app module and controller that fetches model data from a .json file using the $http service.
- A .json file to hold the model data.
File 1: Users.js
:
angular.module('users', []);
.controller('userController', [
'$scope',
'$http',
function($scope, $http, $routeParams) {
$http.get('data.json').success(function(data) {
$scope.userData = data;
});
}]);
File 2: userService.json
[
{
'name': 'Bob Smith',
'age': 26,
'address': 'London',
},
{
'name': 'John Simpson',
'age': 41,
'address': 'New York',
},
{
'name': 'Maria West',
'age': 36,
'address': 'Chicago',
}
];
While Approach B seems more straightforward, some prefer Approach A for its advantages. Can anyone shed light on this?