patternjavascriptMinor
MVC and Services
Viewed 0 times
andservicesmvc
Problem
I'm writing and app in AngularJS and am learning about writing RESTful services. I also want to make sure that I'm understanding the MVC pattern correctly. In my code, this is my take on how I'm implementing MVC.
I have two services that get JSON data from the server. The
Also, is this a good way to implement MVC in Angular?
app.js
services.js
controllers.js
template.html
The code for my app is much more extensive than this, but I wanted to provide a readable example for what I'm trying to understand.
I have two services that get JSON data from the server. The
JSONController then calls these services, and in turn, populates the model to be used in the HTML template. Angular works its magic in the HTML template, which creates the view(?). So, is the view just what the user sees?Also, is this a good way to implement MVC in Angular?
app.js
(function() {
angular.module('myapp', ['ui.bootstrap', 'ngRoute', 'ngResource']);
})();services.js
(function() {
angular
.module('myapp')
.factory('Instance', ['$resource', function($resource) {
return $resource('assets/json/flat.json', {}, {
query: {method:'GET', params:{}, isArray:false}
});
}]);
angular
.module('myapp')
.factory('InstanceStatus', ['$resource', function($resource) {
return $resource('assets/json/inst_status.json', {}, {
query: {method:'GET', params:{}, isArray:false}
});
}]);
})();controllers.js
(function() {
angular
.module('myapp')
.controller('JsonController', ['$scope', 'Instance',
'InstanceStatus', function($scope, Instance, InstanceStatus) {
$scope.flats = Instance.query();
$scope.status = InstanceStatus.query();
}]);
})();template.html
...
{{barKey}} - {{barValue.name}}
Other good Angular stuff
The code for my app is much more extensive than this, but I wanted to provide a readable example for what I'm trying to understand.
Solution
Angular is not exactly a MVC framework, it's a MVW - Model-View-Whatever. You can find an explanation here.
The application has a good structure:
A good solution to work with Restful in angular is Restangular.
I would recommend you some good practices:
The application has a good structure:
- Services to retrieve data from server
- Controller to access the services and provide the view model
- Html for presentation
A good solution to work with Restful in angular is Restangular.
I would recommend you some good practices:
- Add 'use strict'
- Use controller as syntax instead of put everything into $scope
Context
StackExchange Code Review Q#102421, answer score: 5
Revisions (0)
No revisions yet.