What is the point of AngularJS routes? - angularjs

Im creating a website and I chose to do it in AJ.
I have two folders:
Gateways => some php files which retrive data from a mysql db and echos the data as json.
Views => Partial html files which are basically the template for each page. eg Users, Items, etc.
then I have a index.js file which handels the request process and routing:
angular.module('Index',['addon'],function($routeProvider,$locationProvider){
$locationProvider.html5Mode(true).hashPrefix("!");
$routeProvider.otherwise({
templateUrl: '/views/index.html',
controller: "index"
}).when("/items/",{
templateUrl: '/views/items.html',
controller: "items"
})
}).
controller("index",function($scope,$http){
$scope.users = [];
$http.get("gateways/list.php").
success(function(d){
console.log(d);
if(angular.isArray(d)){
$scope.users = d;
}
});
}).
controller("items",function($scope,$http,$routeParams){
$scope.items = [];
$http.get("gateways/single.php").
success(function(d){
if(angular.isArray(d)){
$scope.items = d;
}
});
}).
What is the point of all this route providers in AJ except its elegancy?
Dont they just slow down the site because of number of the requests?
I could just write the php code from the gateways files directly in the templates files?
Am I doing it in the wrong way?

You might be missing the point of using frameworks like AngularJS. They are mostly for Single Page application and ajax intensive. And let me begin that the number of requests don't really slow down application. Remember how Gmail used to be at first without Ajax ? Was it faster than the current implementation ?
Now, when you build a single page application, the app sends req to server and server responds in JSON or XML. In frameworks like AngularJS or any other, server sends the JSON response and we render them using client side templates or DOM. This saves enormous resource from the server side since server doesn't have to parse the array and render the template. So if server had to render a table which has 100 rows, the bandwidth to send to your browser might be 20KB whereas only JSON might be 5KB and a string or DOM template with 1KB to do the rendering. So, you're actually having your visitor's browser do a lot of job. It's all about calculations/computations. Think of a statistics table where there are columns and some computed values to be presented in a data grid. With Client side frameworks, your server would just respond as JSON and browser (with JavaScript) will parse,calculate and render it in template.
As for the question of using a routerProvider, it's essential to bookmark and use browser navigation button. Just like a traditional url has a view, a URL in client side app has a view which should be bookmarkable and should support navigation.

AngularJS, as a JS framework, works it's magic in the client - meaning it's your computer that processes the template files, applying any logic needed. PHP can't do that - it's a strictly server-side language. When you request a PHP "file" via AJAX calls, you don't really get the php file, but the processed output that your servers produces (in this case, a list of users that it will map to an object). If you simply include the PHP logic in your templates, in the best of cases the HTML that angularJS reads will have the list you need to show, but there won't be an actual list model (that angular can filter/change/reorder/save/delete at will) in the angular scope.
But you are right, at the level you are working on it can seem to only complicate and slow down processes (with the minor advantage of simplifying your work). But when things get denser, that modularization (and separating the controller (i.e. Users controller) from the different views it can be applied to (view, list, edit, details, etc) is what keeps your application structured.

I don't think they slow down the site in any way. If your concern is retrieving both the html and the json for each page, that is not how it works.
The html templates are retrieved, compiled and cached only once by angular-js. You can see this using some debug tool, like firebug.
So when the user switches to a different page you only make a json request to the server, which -generally- is a faster and lightweight operation than rendering html server side and retrieving the full html. (anyway, nothing stops you from doing that if it is better for you)

Related

How to load Spring MVC view without reloading js files in it

I have 3 JSP views which all use the same JS file(say app.js).
My UI is on AngularJS which has a different controller for each of the JSP views and also has a custom service which shares information between the controllers. When I load the first JSP, its controller specified in the app.js file saves a value in the custom service. When I load the next JSP file, app.js gets reloaded and so the value that was saved in the custom service is lost.
Is there a way to not re-load JS files? Or is there a better way to go about this?
If you have no control on the server , you can save the data in browser's session storage object to keep data across requests and clean it, when you are done. https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
Javascript variable are not automatically preserved. When you open a new URL in your browser, you do not download again the JS files (they are cached), but they are loaded from scratch in that new page. That means that all previous values are lost, not by accident but by design.
You have different ways to deal with this persistence between page question. One way is server side by using the session:
the js part sends the value to save as parameters of a request
a spring-mvc controller puts that in the session
other views (jsp) or controllers (spring) access the saved value and pass it in the responses
An alternate way is the single page application pattern:
you only load one single full page from the server
the javascript then only sends requests that it processes directly to modify the DOM
Additionally, you could use Windows.sessionStorage to store data client side for the duration of a client session - credits should go to #AmitParashar for this one, more details in his answer.
You can of course mix the 2 patterns (this is commonly done in real world applications), but you must know that every page load will erase all client javascript state
A less common pattern (AFAIK) is to put the state in a cookie. That way it can be shared by the server and the client but:
it is limited to 4k size
you cannot use it for server side security, because it can too easily be forged

Designing a blog using Angular JS

I want to design a blog which will contain several articles. In the home page several tiles will provide links to the articles and when a user clicks on a particular tile with an article's title on it, he will be redirected to a new page having that complete article.
I understand that making a single page application will be of little help in this case.
Will it make sense if I design the whole website using Angular JS? If yes, how should I proceed if I want to design it using Angular JS? Should I avoid using routing since I've learnt that it is primarily used for SPAs, and shall I use $location or something for this instead? Or shall drop the idea of designing using Angular JS at all? Has anyone of you ever designed a multi-page application using Angular JS?
Your guidance will be helpful.
Before identifying the language to use for designing an app, it is important to understand what your app would be doing. In your case, a blog.
and if you analyze the app's functionality, the below three items (there are/could be more but for this use case, these three are sufficient) gain prominence:
Flow
Data
UX
The 1. Flow says that you may not have a SPA but a MPA, which means considering the resources that go into making of the pages, the user experience, it being a blog, a user may not have all that commitment (or patience) to remain with the blog if each click results in a request sent to the server and a heavy duty page served for the user to read through. This means that routes (Express or Angular) are ideal to navigate the user through the blog.
Data
A blog typically contains text and users may perform text search, which means that you need to figure out the right data store for your data ie., text.
This leads you to select the most optimally suited database that is also economical - SQL Server provides for Full text search at a cost of some hefty dollars; MySql does, too, and obviously with no or lesser cost; MongoDb, a document db, gives you the same and with no additional cost (unless you opt for the cloud model). So, SQL Server is not ideal since the app is not (most likely not, being a blog) meant to generate any profits; MySQL is ideal if you use a PHP server and PHP dev; MongoDb is ideal because it enables wrapping the model with the request object thereby, eliminating extensive coding to read the DB and write to the view.
Eg.
(in the router page of the landing Blog page)
var router = express.Router();
var posts = mongoose.model('BlogPosts');
router.get('/get, function(req, res) {
res.json(req.posts); // As simple as this
});
(in the view)
<div ng-repeat="post in infiniteitems">...</div>
(in the controller)
$.ajax({
url: '<url to your route>',
type: 'GET',
dataType: 'json',
success: function(data) {
$scope.infiniteitems=data; // Binds to the controller item in the view
$scope.$apply();
},
error: function() { },
beforeSend: setHeader
});
So, you have the navigation, the view, the data all taken care of with just a few lines of code. More importantly, no innodb or database engine
The code is meant only for explanatory purpose.
Because MongoDB returns a document as JSON and binding a view to a JSON is pretty simple than binding an object or XML values!
Obviously, this means a MVC framework and so AngularJs is the right choice.
UX - Angular Material, when used in conjunction with AngularJS, provides some scintillating designs, colors and animations and the simplicity adds to performance, enhances the UX and renders a freshness to the View (for the user) that is not easily creatable with other technologies.
So, go for Angular.
And also, because MongoDB works pretty well with NodeJS, the whole thing works together which is why they call it the MEAN stack - MongoDB, Express, AngularJS, NodeJS!

Taking server path into account in angular route

I am enhancing an ASP.NET MVC application with angularJS for selected pages. The primary means of navigating the site is still full page request, but some pages contain angular views and associated controllers for interactivity.
Currently, I achieve this by having something like this in the server side view:
<div ng-controller="ExampleCtrl" ng-include="exampleview.html"></div>
However, I would prefer to not inline controller and template definition like that and handle this through routing instead. However, angular routing only uses the client side of the URL (i.e. the parts after the first #). For various reasons, the page URL should remain http://domain.com/Example/Action instead of http://domain.com/Example/Action/#/example (this is just ugly) or http://domain.com/#/example (this will not work because I actually need the server side view as well).
Is there a way to make angular routing take the whole URL path into account instead of just the client part (and works in IE9)?

Are ASP.NET-MVC4 and AngularJs work well together?

Is the combination of technological ASP.NET-MVC4, and AngularJs work well?
About the needs of my app: most of the work of my application view pages with tables of information.
I need to have an easy option to identify each point in the tables on the client side, highlight it, paint it, and request additional information from the server about it.
ASP.NET MVC and Angular.js have nothing in common.
Short answer is yes - they work well together.
You would simply make all your Actions respond with JSON rather than HTML (unless you want HTML in some scenarios)
i.e you write your HTML template, angular controller, etc on the client, and have an Action to grab all the table records as JSON, then load that in your angular controller to populate the table, interact with it all on the client, and send any changes back to the server.
You could replace Angular with any client-side technology if you wanted. Backbone, Knockout, etc.

How to provide configuration to AngularJS module?

Currently I am combining a traditional application with some dynamic parts written using AngularJS. I would like to provide some configuration from my server to my module. In this case I would like to configure the application 'base' URL. All templates can be found at a specific location and this location is determined by the server.
So I tried something like this:
angularForm.config(
function($routeProvider, TemplateLocator) {
$routeProvider.when('/', {
controller : TestController,
templateUrl : TemplateLocator.getTemplate('FormOuterContainer')
});
});
At the server:
<script type="text/javascript">
angular.module('BoekingsModule.config', []).provider('TemplateLocator', function() {
this.$get = function() {
return // something
}
this.getTemplate = function(name) { return 'location...'; }
});
</script>
However, I am not sure this is the right way.
So in short: how can I provide some (external) configuration to a module without having to change the module itself?
There are several things you can do
Render the locations in the js on the server.
Pro: less requests -> better performance (usually)
Cons:
combining server side rendering with an SPA makes the system more complex, leading to higher maintenance costs.
it is harder to properly compress your js files if you want to mix in server side rendering, embedding js in html is also ugly.
Extract the template location to a service.
From this service you could use a $resource to fetch the data from the server in json format. This keeps things simpler, but it could also increase your web server's load.
Wow it has been a long time since. I completely forgot about this post.
So, in the end I decided it was better to use another approach. Like iwein said, combining SPA with server side rendering makes the application a lot more complex. Therefore I extracted the SPA part into a separate application which in turn is referenced from (in my case) the JSP.
When my module needs some additional configuration, it gets it using a REST API. This way the SPA part of the application is completely decoupled from the server-side rendered part.

Resources