Two options, which is better and why:
Example A.
- app module
- service containing model data
- controller to call in data from 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]; }); }]); Example B:
- app module, and controller drawing model data from from .json file through $http service.
- json file to hold 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', } ]; B seems more logical (and easier to me), but I've seen people do A. I presume there's an advantage - can anyone explain it?