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

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

Related

Angular application with Node + Express web API returning JSON resources vs server side template engine

I'm quite new to Node and Express and I'm having some difficulties understanding the concept of server side rendering with template engines (like Jade) or without.
My experience with web development is solely based on Angular applications which consume resources in a JSON format from a RESTful Web API and render the html using Angular's two-way data binding.
What are the pros and cons of this approach, and what are the benefits of rendering html pages on the server when there's so much flexibility with Angular?
This Quora answer is the best description I've found when digging into the topic for several months.
But let me answer your question from the height of my experience:
These approaches are not mutually exclusive to each over, but are complementary.
Pros of server-side rendering:
very speedy initial loading of pages (use AJAX/MVC for subsequent updates);
good for SEO.
Cons:
it may be a bit difficult to set it up initially.
I'd recommend you to build your app in a traditional Angular way, and only add the server-side rendering if you feel your app is slow to respond.

what does AngularJS has to offer to an ASP.NET MVC project? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I heard a lot about how AngularJS is so much better than jQuery for communicating with server.
But all i found was replacing C# controllers and cshtml views with purely client-side javascript files. And i have no interest in that.
is anything that I'm missing?
I am currently using jQuery Ajax for communication between client and server through JSON. I was looking forward for a better solution for this purpose.
Once a controller returns a view, what is sent to the browser is pure HTML. Razor is rendered server side as HTML. Or your action can return pure JSON.
Therefore, whether you want to use jquery, angularjs, or any other JS/HTML based library, there is really no restriction there imposed by MVC. From the perspective of client side code, controller actions are just URLs that return return HTML or JSON.
Additionally, MVC controller actions which return JSON, or WebAPI controllers, are perfect RESTful endpoints for your AngularJS to interact with. If you need HTML fragments for refreshing dynamic areas of a page, then a controller action returning a partial view will come down to the client as an HTML fragment. So your interactive requests through Angular can still leverage your backend architecture of Controller/Business/Data layers.
What Angular Offers MVC
AngularJS offers an MVC application the same thing it offers any web applicaion. It is a great way to abstract the presentation of UI elements from the interactivity of those elements with the backend. The problem with common approaches with jquery is you react to interaction with specific HTML elements via selectors such as $('.someClass').on(... and then in the handler collect information from the element about what was clicked and submit that in an ajax request, and then take the response and update specific elements $('.areaToUpdate).html(response)`.
So you have three concerns not properly separated:
What element responds to interaction(button click, drop down change, item drag/drop)
The interaction with the server to compile a request, submit it, and parse response.
Updating the UI based on the server's response
Often times because of the way we try to make this code less fragile, you are restricted to a logical hierarchy of objects that also matches your UI's HTML element hierarchy. Long story short, the lack of proper separation of concerns means changing any one will impact a chunk of code that has multiple purposes, and thus changes are more challenging because you have certain restrictions imposed due to lack of decoupling.
AngularJS provides a client side separation of these concerns by using a client side model as the intermediary between these concerns. UI interactions update the model, other code responds to changes to the model and makes server requests which update the model in response, and yet other code can respond to those changes and update the UI in response to the model changing. You are free to modify the UI's structure, and have a much more smaller set of code to update to get the UI changes wired up.
The fact that AngularJS is modeled from an MVC pattern makes it seem as though it would be mutually exclusive with ASP.NET MVC. However, they serve two different purposes. ASP.NET MVC provides separation of concerns for the server side querying of data, population of server side model, and rendering of server side HTML. It also provides a great way to support the rendering of JSON or HTML fragments(partial views) that might be leveraged by a client side interactive framework. AngularJS provides a model appropriate for writing clean client side code for highly interactive pages.
Personally, I think they are very complimentary.
Trying to do highly interactive pages with jquery+ASP.NET MVC is doable and can be efficient, but AngularJS adds a lot to the maintainability of the client side code. ASP.NET MVC provides a good framework for your server side logic. Additionally, if you have simple pages that fit a more traditionally PRG pattern or simply rendering HTML content, then ASP.NET MVC gives you an efficient way to quickly implement these pages without the unnecessary boilerplate code you'd need with Angular. In other words, you can choose to use AngularJS only on the pages that will really benefit from it.
You can mix MVC and angularjs with out completely removing MVC controllers.E.g if you have 5 modules on your app create that parent routes on MVC routing.(E.g Students,Teachers,Attendance etc..)
initially render your first view say student view renders through asp.net MVC then include all your JS files(including states related to that module) on that view(e.g students.cshtml)
.JS files related to this module may be
studentModule.js,studentController.js , studentService.js etc.
Do all your CRUD operations on angular JS.
Here your studentService will interact with MVC controller for all your db operations.
Benefit you are getting with this is
you are interacting with your server asynchronously and you can use
all angularjs features like(Directives,resources etc)
You can authorize all your MVC controller actions with asp.net
identity.
-Also to render any html template on state you can call your MVC controller action from templateUrl.return csHtml from MVC controller
action.
There are lot of applications on live using both asp.net mvc and angular js. here are few things i know.you can check some tutorials for better understanding.
.
Angular and ASP.net are both MVC frameworks. They are in a sense at odds with each other - I work on an Angular / ASP.net project where we serve and initial ASP.net view and then let Angular SPA routing take over, but its kind of a hack and I sometimes which we separated the two and had a plain WebApi implementation with Angular front end.
Using AngularJS just for its Http library is like using a sledge hammer when a hammer will do. You are wasting bandwidth in downloading large amounts of unused JS.
I would look to a pure JS library to handle your Http communication if you are unhappy with JQuerys implementation.
Axios is an amazing example of one of these libraries and uses Javascript promises just like Angular - which make the whole process really neat and easy.
Good luck!

AngularJS with JSP

I am new to AngularJS.I have two questions.
Is it possible to use JSP pages instead of HTML in AngularJS.
Is it possible to create a web application using AngularJS without webservices (for fetching data from DB) and use HTTP servlet for that purpose
Is it possible to use JSP pages instead of HTML in AngularJS.
Even if you use JSP the final output will be HTML so you can use JSP in AngularJS but JSP files are mainly used to render the frontend with data that you can do using HTML only in AngularJS.
Is it possible to create a web application using AngularJS without web services (for fetching data from DB) and use HTTP servlet for that purpose
Whether you use plain Servlet or any framework that creates REST APIs, it will be HTTP calls only.
(This is a newbie question which applies equally to all front-end MVVM frameworks. I'll answer it for the general good.)
AngularJS is a front-end framework which runs in the browser. It relies on a server delivering the content (HTML templates, CSS and JS sources) to the browser.
What you use as a server, is entirely up to you. It depends on whether you need server-side dynamic content.
If none is required in that area, you can use a static HTTP server like LightHTTP, or plain old apache, or nginx, or anything else to deliver the AngularJS site to the browser.
But in most you will have some server interaction (i.e. storing / querying stuff in a database, or communication / synchronization with other users, etc). The common approach for that is to deliver HTML/CSS/JS statically and add a bunch of REST interfaces. Flask and Tornado are popular server choices for that, or stuff like spray.IO / akka.http for higher traffic volumes.
In specific cases, you may want to work with pre-rendered HTML templates (usually because you want to dynamically exclude parts of pages for security/user role reasons). Then you need a server-side framework with template rendering. Django, JSP, ASP, pick your favourite.
It seems like you are asking how to use AngularJs in a JavaEE application. And yes it is possible. Only your index.jsp will be in jsp, and all you other views will be in html.
You can then use http requests to fetch data through your servlets.
it can be useful. here are scenarios:
you want to save ram, cpu for mobile phones or machines that doesn't have lots of power. you can partially render page in jsp and keep only minimal in angular.
your team is traditionally jsp heavy and you want to use them and gradually transfer to angular. eg... for i18n rendering jsp seems far better. note that i18n may not add lots of values in angular and you may not want to throw up existing code in jsp.
I have been noticing strong views in stackoverflow and they seem to dismiss everything that doesn't fit in their utopian all new cutting edge. all the angular projects I worked had heavy dose of legacy pages using jsp and it doesn't make sense to rewrite everything from scratch or lay off whole team and start hiring from scratch. and thus, yes, jsp makes sense with angular.

what are the advantages of using 2 MVC architectures(frontend and backend) in same project. AngularJS and Spring MVC

what are the advantages of using 2 MVC architectures(frontend and backend) in same project. AngularJS and Spring MVC.
Without using AngularJs, can I update single div data without loading the entire page? Is AngularJS responsible for updating single <div> data out of multiple <div>s without loading entire page? If so, please explain in detail.
Once you have a single-page application you have to make sure all the different parts of that application are consistent, that's what the MVC/MV-Whatever in the front end is doing for you. That's not an issue in an old-school web application because the relevant state is regenerated with each request, but once the updates are coming in bits and pieces then different pieces of the front end need to be coming from the same model and that model needs to get updated consistently.
Obviously you can implement div updates with raw JavaScript, you don't need frameworks just to do AJAX. The JavaScript frameworks are written in JavaScript, after all. The frameworks and libraries do make things easier by doing things like papering over browser inconsistencies and providing convenient and useful features (like databinding in Angular).
The server-side MVC does become less complex and involved than it was in the old-school web application, you have less POST-Redirect-GET going on, the front end is more in control about what it is asking for. The front-end application is decoupled much more from the server-side because that whole server-side view layer of JSPs or Facelets or whatever is greatly reduced or just missing, instead you have services supplying JSON over HTTP and there is a much more limited, well-defined contract.
You can update a single element of your page without using AngularJS. As an alternative, for example, you can use JQuery.
You should wonder for the best approach for your project. This answer explains very well the differences between this two approaches.
As an aside note, AngularJS is not exactly a MVC architecture. Instead, the community has decided to call it MVW (Model View Whatever). Check this source for more details.

What are the best practices for separating concerns with Angular and Express?

I feel like both Express' and any MEAN stack tutorials gloss over this, so I decided to ask here.
See also these similar SO posts:
Why would one want to use Express instead of AngularJS?
Angular and Express routing
Using plain HTML with Angular directives/attributes as the view engine in Express, what's the best practice for rendering page partials in a single layout template with regards to routes?
How do you do this with HTML/Angular as your view engine?
In Jade, you'd do something like block content.
Do you use the Angular Router, ng-view and use directives?
If so, what's the point of Express? Just a server? Why not just use Connect?
P.S. If you're wondering about Jade or EJS, I'm just learning Express, and Angular, so I'm trying to keep language abstractions to a minimum.
I guess my confusion originates from the overlaps between Express and Angular in regards to templating and routing, but Express focuses on the server-side, and Angular, the client. For someone just learning these, it's tough to know how to implement when everything is so wide open.
I'm looking for detailed, specific implementation code examples that use best practices when it comes to separation of concerns. Seeing it and having it explained in context is how I learn best from others.
Check out angular-blocks if you want jade-like blocks:
https://github.com/wmluke/angular-blocks
It's important to understand that Angular and YOUR_SERVER is generally irrelevant. It's a matter of "where do my files go". As single-page application suggests, it is a single static route. I'm sure Connect would handle this just fine, but the server portion of your application likely has more concerns than simply serving a static page. Authentication, business logic, API routes and other concerns come into the picture at some point, so Express (and its ecosystem) makes a lot of sense.
Your single-page application will definitely have its own routes. These are unrelated to your servers routes, which will include the static route to the Angular application page, and also any routing for API calls that the Angular app will be making.
It's important to understand that you are writing two distinct and separate applications, connect via an API. The fact that your Node server is delivering the static HTML and JS is, for the most part, coincidental. The Angular application should be considered, and developed, in an isolated, decoupled way for best results.
Express and angular serve totally different purposes.
In most MEAN-like stacs situation (for example just express-angular), express acts as server PLUS API provider.
You use app.get('/') with any server side templating like jade (just to have cleaner html files...), then You use app.get('/partial/:name') to handle all partials with same template language.
then, You use app.get('/api/anyapi1'), app.get('/api/anyapi2') to provide whole api to angular - no matter what it will be - some mongo or postgres handling, or just Your static json files.
In new express4 You can also create dedicated api route with:
var api = express.Router();
api.get('/somget', function(req, res) {
res.send('some json');
});
// init api route. all api routes will begin with /api
//(like above api.get will be at /api/somget)
app.use('/api', api);
You can also deal with sessions and authorization on express side, and whole awful lot of stuff, that shouldnt or cant be done on client side.
Hope it helped.
EDIT: speaking shortly: express is backend with http server, other services and api, and angular is whole frontend which consumes what backends provides.
Having such separation You can even provide that backend api to others, or build different services on top of it.
Correct, the MEAN stack puts an emphasis on making most of your logic on the front end. Your express server will act as a mule to save, read, validate, and delete data based on the get and post request you make from the front end.
The idea is to have all your front end code in a public folder of your express app.
`app.use(express.static(__dirname + '/public'));`
Then simply make a route that renders the index file as such
`app.get('/',function(req,res){
res.render('index')
})`
With this in mind you may we wondering if there is a solution that can generate an api for you so that you just name your models and the rest is done via angularjs services. There is.. http://loopback.io/ just name your models, relationships and restrictions. It will generate an enteprise level api for you to play with.
For a complete working example on how routing is done and how to model your app check out this tutorial: http://www.ibm.com/developerworks/library/wa-nodejs-polling-app/

Resources