Você está na página 1de 15

AngularJS app for .

net developers
Introduction
We have a user story that is very simple. A user story is a software requirement written from the
point of view of an application user that follows a constrained format: "As a (user role) I want
(feature/goal) so that (I have this benefit/specific outcome)". The words between the brackets are
replaced with requirements specific to your application. Hope so a car rental management
application is a good project to build for this article. We know an application involved with two
types technologies one is server process technologies and another is client process technologies.
Suppose we know only client process technologies like:Html,Css and Javascript, except those we
don't know anything about server process technologies but we know how to use server response
data with html . Our focus is how to build a client side application with server response data.
We are going to use best JavaScript framework for purpose of data communication with server to
client and client to server that is AngularJS which helps build client side web applications.
AngularJS is an open-source project which means it can be freely used, changed and shared by
any one. AngularJS is an excellent framework for building both single page applications and line
of business applications.
There are a lot of stuff, to build in this application so I will break this article in the following
basic sections:
1. What we are going to build: Describe the purpose and the requirements of our application.
2. What we are going to use: The list of technologies for all server, front-end side
libraries and frameworks.
3. Application architecture: The entire design of our application from the lowest to the
highest level.
4. Application: Start building the core application components step by step
5. Discussion: Well discuss the choices we made in the development process and
everything that you need to know to scale up the application.

For whom the article is


This article is for .NET Web developers, who wants to learn how to build Applications by
AngularJS using existing service. However, if you want to learn how to build a real, production
level Application from scratch, then this is your article that you were looking for.

What we are going to build


We are going to build an Application to support the requirements of a Car-Rental store that is a
store for customers visit, pick and rent cars. Days later they come back and return what they have
borrowed. This Web application is supposed to be used only by the rental store's employees and
that's a requirement which will affect mostly the front-end application's architecture. Let's see the
requirements along with their respective screenshots:

Requirement 1:
1. Car related information added to the system must be displayed.
2. For each car, relevant information and functionality must be displayed.

Pic: Car-Relevant-Information

Requirement 2:
3. There will be 2 pages related to customers. One is to view and edit them and another is for
customer list display.

Pic: Customer-List.jpg

Pic: Add-Edit-Customer.jpg
Requirement 3:
4. All cars must be displayed with their relevant information
5. When employee decides to rent a specific car to a customer through the Rent view, it should
be able.

Pic: Car-Rent-List.jpg

Pic: Employee-Rent-Car.jpg

What we are going to use


We have all the requirements, now we need to decide the technologies that we are going to use in
order to build our app application.
Server side:
We have service for serving data to Web clients (browsers)
Client side:
AngularJS as the core JavaScript framework

AngularJS is a JavaScript framework that helps to build web applications. AngularJS is an opensource project which means it can be freely used, changed and shared by any one. AngularJS is
an excellent framework for building both single page applications and line of business
applications.
In the market we already have several other JavaScript frameworks that help us build to web
applications, so the benefit of using an angular is over those JavaScript framework that we
already have, dependency injection is something AngularJS does quite well, if youre new to the
concept of dependency injection dont worry well discuss in detail with examples in later
section. There is two way for data binding one of the most useful feature in AngularJS that way
data binding keeps to model and the view which sink at all times so that it means changes to the
model updates the view automatically and similarly a change to the view updates the model.
Angular application cord model-view-controller with Angular, it is very easy to develop

applications in a clean MVC way, where all of you have to do is split your application called
MVC component that is model, view, controller and connect them together is done by angular
automatically and there are many more benefits as well like controlling the behavior of Dom
elements using directives and the flexibility that angular filter provide.
In our app we will use angular directives, filters, models, controller and routes.
Bootstrap 3 as the CSS framework for creating a fluent and mobile compatible interface.
Angular-ui is hosted at http://angular-ui.github.io and is one of the better known AngularJS
companion libraries. It has several AngularJS modules, such as UI.Utils and UI Bootstrap that
can be used independently from one another. The UI.Utils module provides directives such as
jQuery Pass-through. This directive allows the use of jQuery functions or plugins directly in
AngularJS, without having to create a new directive.
Moment is as popular date utility library, I initialized the start and end dates using this library.

Application architecture
We have seen both application's requirements and the technologies that we are going to use.
Now it's time to design a decoupled and scalable solution. There are two different designs we
need to provide here. The first one has to do with the entire project's solution structure and how
is this divided in independent components, the second one has to do with the Application
structure itself that is how angularJS folders and files will be organized.

Let's take a look at the solution architecture

Pic: Solution's architecture


Now let's take a look at the application architecture

Pic: Application architecture (angularJS)

Creating a car rental management application

Create web application


Now we are Using Visual Studio with NuGet to manage AngularJS and related libraries.
Visual Studio 2013 or update has introduced a new and simpler way to create web development
projects. It is now possible to create an empty web application that does not have to choose a
web framework right from the beginning. The following screenshot shows the new web project
dialog box:

Pic: Empty-Web-Application.jgp

Include necessary package libraries


We will use this dialogue box to create a new web project that does not have any web framework
selected, just like in the previous screenshot. Next, we will include the necessary files like:
AngularJS, Bootstrap. To add a reference to a local version of the AngularJS library, we need to
use the NuGet Package Manager from Visual Studio.
We need to run the following command in NuGet Package Manager Console:
Install-Package AngularJS.Core -Version 1.2.15

We include bellow libraries in our project from Nuget package manager


<packages>
<package id="Angular.UI.Bootstrap" version="0.14.3" targetFramework="net452" />
<package id="AngularJS.Core" version="1.4.7" targetFramework="net452" />
<package id="AngularJS.Route" version="1.4.7" targetFramework="net452" />
<package id="bootstrap" version="3.3.5" targetFramework="net452" />
<package id="jQuery" version="1.9.1" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0"
targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452"
developmentDependency="true" />
<package id="Moment.js" version="2.10.6" targetFramework="net452" />
</packages>

The main menu for our application will contain three links to the three main views: Rentals,
Customers, and Cars. This menu should be responsive and adapt to smaller screen sizes because
we used the nav-bar component and kept the recommended markup. However, if you realize the
browser to a width of under 768 px, you will notice that the menu collapses and that this does not
have any effect on the button that should display it again. The functionality required for this
resides in a Bootstrap JavaScript file called collapse.js, which does not work with AngularJS in
its current form. Furthermore, this is where the AngularUI, UI.Bootstrap module comes to the
rescue. To install it in the project, we need to run the following command in NuGet Package
Manager Console and add a reference to the scripts/ui-bootstrap-tpls-0.10.0.js location in
index.html:
Install-Package Angular.UI.Bootstrap -Version 0.10.1

Application
Now we have necessary libraries in our project, we have index.html page now to get start with
angular, there are two simple steps the first step is to add a reference to the angularJS so Im
going to drag and drop the angular.js file on my page within the hear section so we have a
reference to the AngualJS and the second step is to include ng-app attribute somewhere within
the HTML, so Im going to include that within the HTML element. Next question that comes to
mind is, what is this ng-app attribute? In angular ng-app is called a directive there are many such
directives in angular and you can find the complete list of directives in angularjs.org

ng-app directive is a starting point of angularjs application, angular framework first check for
this directives somewhere in the HTML page, if ng-app directive is found then angular
bootstraps itself and starts to manage the sections of page that has ng-app . We add ng-app in our
HTML element so that everything will be manage by angular under this element.
Now we work to create a module, controllers and register a controller with the model. A module
is a container for different parts of your application i.e. controllers, services, directives, filters
etc. Module is required because it's the main method in other types of applications for example a
.net console application that has a main method which is the entry point into the application and
it's the responsibility of the main method to wired together different parts of the application.

How to create a module?


Use the angular object's module() method to create a module, we create module in our app.js file.
var myAppModule = angular.module('myApp', []);

How to create a Controller?


Controller is a JavaScript function, the job of the controller is to build a model for the view to
display. Model is nothing but data, in a real-world application control may all into service which
retrieves data from the database, so how to create a controller and register it with module in an
angular application, simple create a JavaScript anonymous function like we create in our
controllers folder applicationController.js file.
myAppModule.controller('ApplicationController', ['$scope',
function ($scope) {
$scope.isMainMenuCollapsed = false;
}
]);

Route
Our main menu contain three links to the three main views: Rentals, Customers, and Car. So one
of the most distinctive features we need for our application that capable to client-side-based
navigation between different views. If the browser switches between different application URLs,
the current view should be updated seamlessly without a page request being sent from the server.
Luckily AngularJS has built-in support for this feature, which is known as routing.
Now the index.html file has a new directive, ngView, that replaces the original players markup.
This directive will render the view that matches the current route, and you can have only one in
an Angular Application. The last step is to configure the routes in the application module config
section by setting them up with the $routeProvider component, those are available in our
project App folder app.js
myAppModule.config([
'$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'scripts/app/views/default.html' });
$routeProvider.when('/cars', { templateUrl: 'scripts/app/views/carsIndex.html', controller:
'carsController' });
$routeProvider.when('/cars/new', { templateUrl: 'Scripts/app/views/carsEditor.html',
controller: 'carController' });
$routeProvider.when('/cars/:carId/edit', { templateUrl:
'Scripts/app/views/carsEditor.html', controller: 'carController' });
$routeProvider.when('/customers', { templateUrl:
'scripts/app/views/customersIndex.html', controller: 'CustomersController' });
$routeProvider.when('/customers/new', { templateUrl:
'Scripts/app/views/customerEditor.html', controller: 'CustomerController' });
$routeProvider.when('/customers/:customerId/edit', { templateUrl:
'Scripts/app/views/customerEditor.html', controller: 'CustomerController' });
$routeProvider.when('/rentals', { templateUrl: 'scripts/app/views/rentalsIndex.html',
controller: 'RentalsController' });
$routeProvider.when('/rentals/new', { templateUrl: 'Scripts/app/views/rentalsEditor.html',
controller: 'RentalController' });
$routeProvider.when('/rentals/:rentalId/edit', { templateUrl:
'Scripts/app/views/rentalsEditor.html', controller: 'RentalController' });
}
]);

Create views
Now we will create the following separate views for Cars:
An index view to display all cars.
A new view to create a new car.
An edit view to edit an existing car.
After these views are implemented, we need to create similar views for customers and rentals,
those views create process are same as cars view, we implement only cars view but article
attachment project contain customers and rentals views implementation.
We had a single controller called ApplicationController in index.html file, and the views
defined in app.js were not attached to any other controller. The ngRoute module allows you to
associate a controller with a view that is suitable for the current route. I will create a
carsController controller, which will be instantiated whenever the carsIndex.html file is
rendered. The following code shows the initial definition of the carsController controller:
var myAppModule = angular.module('myApp');
myAppModule.controller('carsController', ['$scope', 'carsService',
function ($scope, carsService) {
$scope.cars = carsService.getcars();
}
]);

Now we use a table element with Bootstrap styles, which will give the rendered content striped
rows and visible margins. The rows will be built using the ngRepeat directive in HTM.
<table class="table table-bordered table-striped table-hover table-responsive">
<thead class="bg-primary">
<tr>
<th>#</th>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Daily rent price</th>
<th></th>
</tr>
</thead>
<tbody>

<tr ng-repeat="car in cars">


<td>{{car.id}}</td>
<td>{{car.name}}</td>
<td>{{car.typeName}}</td>
<td>{{car.quantity}}</td>
<td>{{car.rentPrice | currency}}</td>
<td>
<a class="btn btn-danger role="button" href="#/cars/{{car.id}}/edit"><span
class="glyphicon glyphicon-edit"></span></a>
</td>
</tr>
</tbody>
</table>

The Cars new view


With the index view in place, it is time to implement the functionality to add a new car. We need
to add a new route with a new view and new controller in app.js. We can use the following code:
$routeProvider.when('/cars/new', { templateUrl: 'Scripts/app/views/carsEditor.html', controller:
'carController' });
Access to the new view will be provided through an Add new car button on the cars index view,
and through a similar button on the default application view.
As we have two controllers working with car objects, it is good practice to create a carsService
service that will contain all the business logic required to create, read, and update cars. The
service does not have any access to the controllers, but it will be able to access other application
services and AngularJS built-in services. The following are the methods of the service:
getcars(): This method returns an array of cars, including the initial ones and any added ones
getcarTypes (): This method returns an array of car types to be used in selected elements
createcar(): This method creates an initial car object to be populated with values by the user
addcar(): This method adds a valid, new car object to the existing list of cars.
Now this service used by the application as a dependency.
With all this in place, we can now implement the new view. For the HTML, we will use the
styling specific to the Bootstrap form, and for form validation, we will use the built-in,
AngularJS-form-related directives. This is a powerful combination.

The Cars edit view


To implement this view, we will use the index view as a start point. We will add a new column
with an Edit button that will navigate to the edit view. The HTML for this form will be almost
identical to the one in the new view. The differences will be in the form title and in the addition
of a disabled form control that shows the car-ID. We will use the same HTML file and
controller, and the routing will be changed to the following code:
$routeProvider.when('/cars/:carId/edit', { templateUrl: 'Scripts/app/views/carsEditor.html',
controller: 'carController' });
Note: the carId route section, which will be made available as a property in the built-in
$routeParams service. The 'carController' controller will now use this service to detect whether
the form is in the create or edit mode, as shown in the following code:
$scope.isNew = !$routeParams.carId;
We can now use this scope property to display a new form control in the edit mode and hide it in
the create mode, as shown in the following code:
<div class="form-group" ng-show="!isNew">
<label for="inputId" class="col-md-2 control-label">Id</label>
<div class="col-md-1">
<input type="text" class="form-control" name="inputId" value="{{car.id}}"
disabled>
</div>
</div>

When we navigate to the car edit application route, the following screenshot will be displayed:

The same way we can create Customer and Rentals view.

Discussion
Scaling
There are 2 main things I would like to discuss about the application that we have created. The
first one is talk about scaling the application to support more roles. I'm talking about featurelevel scaling for example suppose that you have an extra requirement that this web application
should be accessible by external users too, the Customers. What would that mean for this
application? The first thing popped up to my mind is more templates, more Web API controllers
and last but not least even more JavaScript files. Guess what, that's all true. The thing is that after
such requirement our car-rent application will not be entirely smart Application. It could, but it
would be wrong.
Let me explain what I mean by that. From the server side and the Web API framework, we have
no restrictions at all. We were clever enough to create a custom membership schema with custom
roles and then apply Basic authentication through message handlers. This means that if you want
to restrict new views only to customers, what you need to do is create a new Role named

Customer and apply an [Authorize(Roles = "Customer")] attribute to the respective controllers or


actions. The big problem is on the front-end side. You could add more functionality, templates
and controllers upon the same root module car-rent but believe me, very soon you wouldn't be
able to maintain all those files. Instead, you can simply break your application in two Single
Page Applications, one responsible for employees and another for customers. This means that
you would have two MVC views, not one one more action and view in the HomeController.
Each of these views is an application by itself and has its own module. And if you wish, you can
go ever further and adapt a new architecture for the front-end side of your application. Let's say
that both the Admin and Customer roles, require really many views which means you still have
the maintainability issue. Then you have to break your App even more and have a specific MVC
View for each sub-feature. All the relative sub-views can share the same Layout page which is
responsible to render the required JavaScript files. Let's see the architecture graphically.

Fig: extended-architecture.jpg

Conclusion
Thats it, we finally finished this article having described step by step how to build an
Application using AngularJS with existing service. You can download the source code for this
project we built here where you will also find instructions on how to run the car-rent application.
I hope you enjoyed this article as much I did writing it. Please take a moment and post your
review at the comments section.

Você também pode gostar