Designing a blog using Angular JS - angularjs

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!

Related

Is there any need of learning views and template engines in express when we have already learn angular in the MEAN Stack

I am learning MEAN Stack. I started from learning Angular(from angular.io) now I am learning node.js and express.js
My question is, if there is angular for front end in MEAN Stack then why there are views and template engines in express.js at back-end? Are they alternative for each other or complements each other? what is the boundary for the role and responsibility of these two?
I am looking forward for someone's help in clarifying of my concept for role these two technologies(express' views and angular) used in mean stack.
In order to answer your question, let me explain what is angular and what are template engines in express?
What is Angular?
Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop.
what is template engine?
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.
So,
Angular is a framework with a templating component baked in. You use it to create Single page Web Applications which means that DOM modification is happening on the client side and the app exchange with server only data. If your concern is template it is plain HTML.
Whereas, template engines' rendered views are sent to client each time by server whenever request is made each time a new page is rendered on server and sent to the client which is Great for static sites but not for rich site interactions.
If there is angular for front-end in MEAN Stack then why there are views and template engines in express.js at back-end?
This is because not every time generating views from angular is recommended sometimes it is better to use Template Engines to generate views and send the rendered page to a client, generating views at client side has its own pros and cons and generating views at server side has its own.
Generating views using template engines (i.e. at server-side):
pros:
Search engines can crawl the site for better SEO.
The initial page load is faster.
Great for static sites.
cons:
Frequent server requests.
An overall slow page rendering.
Full page reloads.
Non-rich site interactions.
Generating views using angular engines (i.e. at client-side):
pros:
Rich site interactions
Fast website rendering after the initial load.
Great for web applications.
Robust selection of JavaScript libraries.
cons:
Low SEO if not implemented correctly.
The initial load might require more time.
In most cases, requires an external library.
So, after knowing the pros and cons, you yourself can better decide that in particular case which one is better for you. Mean Stack has provided options for developers.
As far as your question regarding the role of these two technologies is concerned, Angular is a lot more view generator only, It has features like routing, it as services two-way data binding etc while the template engines are meant to render HTML so that it can be sent to the client.
I hope you will find this answer useful.
References:
what is the template engine?
what is angular?
pros/cons
Angular is a full-fledged front-end framework that comes with its own way of doing templating, using angular-specific markup in your HTML. If you use Angular as your framework, you're more or less stuck with their way of templating within the Angular portion of your application.
Angular Features
It is a framework written in Javascript language
Manages state of models
Integrates with other UI tools
Manipulates DOM
Allows writing custom HTML codes
It is meant for javascript developers to create dynamic web pages in a quick time
NodeJS
It serves the web
It is runtime built on javascript engine in google chrome
It can be considered as a lightweight server which can serve client requests in a more
simpler way than java does
It performs communication operation with databases, web-sockets,
middleware etc.
Why we use angular for Tempting not Express/Node tempting Engine
Server-side rendering is the most common method for displaying information onto the screen. It works by converting HTML files in the server into usable information for the browser.
Whenever you visit a website, your browser makes a request to the server that contains the contents of the website. The request usually only takes a few milliseconds, but that ultimately depends on a multitude of factors:
Your internet speed
how many users are trying to access the site and
how optimized the website is, to name a few
Once the request is done processing, your browser gets back the fully rendered HTML and displays it on the screen. If you then decide to visit a different page on the website, your browser will once again make another request for the new information. This will occur each and every time you visit a page that your browser does not have a cached version of.
It doesn’t matter if the new page only has a few items that are different than the current page, the browser will ask for the entire new page and will re-render everything from the ground up.
How client-side rendering works
When developers talk about client-side rendering, they’re talking about rendering content in the browser using JavaScript. So instead of getting all of the content from the HTML document itself, you are getting a bare-bones HTML document with a JavaScript file that will render the rest of the site using the browser.
This is a relatively new approach to rendering websites, and it didn't really become popular until JavaScript libraries started incorporating it into their style of development.
See Examples HerePratical Example
Basically template engines in Express are mostly used for displaying 404 and other server error messages. I find them ideal for such use cases. Using template engines for complex front end rendering is bad and not a good practice.
Express JS is a web framework on top of nodejs http module. Whereas Angular JS is a front end framework which doesnot depend on NodeJs server to run. Conceptually both are similar in few features like routing whereas implementation is different

URL handling in a Hypermedia (HATEOAS) driven AngularJS application

We are looking for some advice on handling URLs (and the state related to each URL) in a web application backed by a HATEOAS REST API, more specifically on
how to avoid having the web application URLs coupled with the REST API URLs
how to handle multiple resources in a single view
But let me first provide some more context:
We are building an Angular web application on top of a REST layer with Hypermedia constraint. (Note: I prefer simply using the term 'Hypermedia (constraint)' over HATEOAS).
As dictated by the Hypermedia constraint, the available actions and links in the application at any point in time are provided by the REST API. So the web application should not contain any hardcoded urls of the REST API, except for the 'root' (assuming that concept really exists in a REST API).
On the other hand, each page in the web application needs to be bookmarkable. So we cannot create a black-box application (with a single url and all state changes handled in the SPA without changing the URL). This means the web application also has its URL space, which needs somehow to be mapped to the REST API URL space. Which is already a conflict with the Hypermedia idea.
In the Angular application we use UI Router for handling application state. Here is how we got it working:
We only define states, no URLS
We defined a $urlRouterProvider.otherwise handler that will map the current web application URL to the corrsponding REST API URL, retrieve the representation of the resource that corresponds with that REST URL and pass it to the controller (in $stateParams).
The controller can then use the data (and links and actions) in the representation, just like it would if it would have made the REST call itself (or through a service)
So far so good (or not really) because there are some downsides on this approach:
The Web application URLs are mapped to the REST API URLs, so both URL spaces are coupled, which conflicts with one of the basic assumptions of using Hypermedia constraint: we cannot change the REST API URLs without having to change the web application.
In the $urlRouterProvider.otherwise handler we retrieve the representation of the current web app URL. But in some cases we have two resources in a single view (using UI Router nested states): for example a list of items and a detail of a single item. But there is only a single URL, so only the representation of the item detail is retrieved and the list of items remains empty.
So we would love to hear some suggestions on how we could improve on our approach in handling the two URL spaces. Is there a better way to make the REST API dictate the (available) behaviour of the web application and still have bookmarkable URLs in the webapplication? Because now we have some kind of hybrid approach that does not feel completely right.
Thanks in advance.
Regards,
Luc
that's a tough setup. Roughly you want bookmarks into your API, and RESTful systems somewhat discourage bookmarks.
One possible solution is a "bookmark service" that returns bookmark (bit.ly like) urls for the current resource being presents that are guaranteed to be fowards compatible because as you may change the canonical url structure, the bookmark service can always translate the bit.ly like url into the canonical url. Sounds complicated, but we see this all the time and we call them SEO urls eg: /product-name/ maps to products/ today, but may be /catalog/old-products/ tomorrow.
How you match that up to a UI that shows 2 resources the first being a list of summary like resources, and the second being a specific resource get's really tricky. I would expect such a page to know contain the state of what's it's displaying in it's url (probably in the fragment). As such since it's [likely] the controller that processing such commands it probably needs both (the list resource and the expanded resource) as input. I bet the url would look something like:
list=http://path/to/list/results&expand=http://self/link/of/path
So the last part you have is to make sure that works going forwards. Again this is the bookmark problem. What i may suggest if you don't want to build a bookmark service is that given you want to have such bookmarks you need to transition people to the new URLs. When a request is made to http://path/to/list/results and you want to switch that over you should be 301 redirecting them to the new canonical url and the app should be updating the bookmark. such a redirect can include the &flag=deprecate_message param to trigger the presentation in the UI that the client's bookmark is old and should be replaced. Alternatively the response can be internally forwarded and the deprecation flag & canonical (or latest) link included in the response to the old URL. This causes a phased transition.
In summary: I have yet to see HATEOAS be a cure all for backwards & forwards compatibility, but it's much better than the existing techniques. that said you must still make decisions in v1 of your API about how you want your users to move to v2.

Aggregated Data vs RESTful Resources for AngularJs SPA

I am working on a single page app using AngularJs Framework.
The website is kind of social networking and thus consists of various kinds of data to be fetched from server.
Will it be good to be RESTful and make each entity a 'resource' or implement other way to get 'aggregated JSON' response, since RESTful results in too many calls ?
If non-RESTful approach is used, ( say by using $http service ), then how can I still maintain the modular architecture of app.
Consider example for clarification:
let the server return:
{
user: {
name: ....
....,
projects: [{
....
....
}],
...
}
}
How can I create modules such as User and Projects, each with its own functions and logically separate and independent.
Its almost similar to making single $http request and distributing response to many services.
Any help is appreciated.
Disclaimer - I am by no means a REST expert or purist
This is a very good question and something I struggled with as well. I just couldn't justify having X number of REST calls to display a single form/page, where X could sometimes be fairly large. The solution I ended up with which seems to work reasonably well in my case was a hybrid approach. I use aggregates (View Models) to render the forms/pages, these View Models I get from the server with a single API call. For create/update/delete operations I extract the actual resource from the View Model on the client and post that using a more RESTful approach.
This gives me best of both worlds, low number of API calls to display page, RESTful approach on post which reduces network overhead.
In addition to the above I use an approach I saw on breeze.js documentation which seems to work really great as well, on application startup I load all commonly used static lookup data (typically data used for dropdowns/select lists) in a single LookupsAggregate and cache that on the clients. This model is then available from the start and no need to refetch them everytime you need to display a dropdown/select lists.

Jinja2, Backbone.js and progressive enhancement

I have a working website build on top of Google App Engine (Python + Jinja2 template engine). I would like to start redesigning it to be single page application using Backbone.js and Underscore.js. The goal is to use progressive enhancement strategy.
The site will still be rendered using backend on the first visit. And then if the browser supports JavaScript the Backbone.js will take over.
I decided to do it this way for two reasons. First all the links I already have will stay intact and second the Google indexing bot will be able to crawl the site content.
I have two problems with this approach:
I need to have two templates for almost everything on my site one on the backend (Jinja2) and one on the frontend (Underscore.js). I was wondering what are the best practices in cases like this? Is there anything you can suggest to avoid having two templates for everything?
How do I load the templates for the frontend to use Backbone.js + Underscore.js? I can load them all in the initial request or request them asynchronously when they are needed.
I appreciate any thoughts!
Thanks.
Some resources:
http://ricostacruz.com/backbone-patterns/
This one describes how to bind Backbone.js to existing HTML:
http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-2-progressive-enhancement-with-backbone-js/
So I recently(this year) went through a similar situation. I'll let you know a head of time that #1 is an incredibly tough thing to deal with. Keep in mind, that you not only would have to duplicate your templates, but ALL business logic surrounding your site. For example, let's say you allow users to add comments on a particular page. Using the method you described, you would have to both have a comment template on the server-side and the client-side, and additionally, duplicate the logic required to add/delete/edit a comment on both the client and the server(to accommodate users with and without javascript). Duplication of the templates is easy using Jinja2 function blocks, but the duplication of the logic is where it gets interesting. I attempted to do just that, and ended up doing a full re-write a few months later.
So the advice I would give to you is ditch the idea that you can support both javascript and non-javascript users. Make your site for one or the other. I personally chose to go the javascript route myself. This leaves you with two options. Make a single page app, or make an app that largely leverages javascript for functionality, but renders everything server-side. There are probably a number of other options, but those are the two most popular that I have seen. I went with the second option. So what I do, is the initial page load is done by the server. Backbone.js then consumes each element and makes models and views out of them. This is largely done leveraging data attributes. So for example to create a comment view I would have an element like this:
<div class="comment" data-id="1" data-body="You Suck"></div>
I would then consume said comment, and create a model out of it like so:
var CommentModel = Backbone.Model.extend();
var comment_el = $('.comment');
var comment_model = new CommentModel($(comment_el).data());
Finally, I would back a view with that created model, which can then add functionality to the site:
var CommentView = Backbone.View.extend({
initialize: function() {},
edit: function() {},
delete: function() {}
});
var comment_view = new CommentView({
model: comment_model
});
Then you might be asking, "What if I need to re-render something, don't I need client-side templates for that?" Nope. Client-side templates are a pretty new thing. I personally try to avoid them as I don't think we're quite there yet, and I have always felt that single-page apps are just not responsive enough for my tastes. I'm sure there are plenty of people who would disagree with me on that, but that's the stance I took with my most recent project. So that being said, I render everything on the server and send the html to the client in the form of JSON, which I then inject into the DOM. So I have a ton of api endpoints, which return JSON to my Backbone.js code. This is what is currently working out for me, but this problem is largely situational usually. You have to really look at what your needs are. For it's worth, I largely based my current system off of what Twitter eventually decided to do after trying the whole single-page app thing. You can read about it here.

What is the point of AngularJS routes?

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)

Resources