Angularjs
Angularjs
By Juned Laliwala
● What is AngularJS?
● A Complete Client-Side solution
● The Zen of Angular
View
In Angular, the view comprises of HTML elements and directives. View is nothing
but the display that we want to see in our browser is view. Other than markups,
every view has as an expression (with curly braces), which is tied up to the scope
object.
<div ng-app="myApp" ng-controller="myController">
</div>
The above piece of markup, also known as Template in Angular, when bound,
complied and loaded on the browser is then called the view.
Controller
The controller actually controls the entire business logic of your application. The
initial stage is set here, that is, it initializes and registers the application by
creating a new Angular Module.
(function (){
var app = angular.module(‘myapp ’, [ ]);
app.controller(‘mycontroller’,function(){
}
}();
In the above example, we can see that we have made one module named
“myapp”. Inside this module we have created one controlled named
“mycontroller” which is made using “app.controller”.
<div ng-app="">
<p>
<label>Current Bid Value</label>
<input type="text" ng-model="bid" ng-init="bid ='75'" />
</p>
<p> ${{bid}} </p>
</div>
2.1.3. Templates
In Angular, a template usually means a view with HTML elements attached to
Angular Directives , add markup for data binding using expressions (with curly
braces).
<div ng-app="BiddingApp">
<input type="text" ng-model="bid" />
An Angular template is exactly the same as HTML, except for its attributes. If we
want to make it dynamic we have to work with model and controller.
Now let us see the main elements and the successive attributes which basically
makes up the template.
b) Markup – Binding the view with a model using the curly braces {{ bid }}
(expressions) is the markup.
c) Filters – Filters are useful for formatting the value in an expression. It is very
useful. I have explained about filters later in this article.
d) Form Controls – We can use Angular Form Controls to validate user inputs.
Let us assume the form has an input field, which accepts email ids only. The form
control will validate the input and display a message if the value is invalid.
2.1.4. Directives
Angular Directives are attributes applied in the View. Attached to HTML
elements, the directives augment the elements with new beha0viors. Did you see
the above examples; each element has directives, prefixed with ng-. Whenever we
attach a directive with an element, it tells AngularJS that it is a part of Angular
app and Angular treats it that way.
Here in this example, I have used useful directive, called the ng-include, to add
the content of an .html file.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"><
/script>
</head>
<body>
<div ng-app>
<div ng-include="'hello-world.htm'"></div>
</div>
</body>
</html>
2.1.5. Expressions
Angular Expressions are JavaScript like expressions, however with lots of
difference. Written inside two curly braces, these expressions will bind Angular
application data to HTML elements.
2.1.6. Modules
In the section of the MVC, we have seen the architecture which helps in designing
Angular application by splitting the app into little manageable structures. The
Modules are pillar of this architecture. A module creates a well-defined structure,
which will keep everything organized, at one place.
A single application may more than one module. By creating a new module, each
application is first initialized and registered.
<script>
// INITIALIZE FIRST APP.
var mailApp = angular.module('myMails', []);
2.1.7. Scope
A Scope is a JavaScript object that sits inside the model, and delivers data to the
view. The view‟s expression will receive the value(s) from the $scope and display
the result exactly where the expression is located.
<div ng-app="myMoney" ng-controller="moneyController">
<p>Dollar Today: {{ rate }} </p>
</div>
<script>
var bullionApp = angular.module('myMoney', []);
bullionApp.controller(
Output
Dollar Today: 62.15
See, how the expression property rate in the view is accessed inside the controller
using $scope. The variable $currency is passed to the controller and assigns the
value to the property rate.
2.1.8. Filters
An Angular Filter modifies the data before presenting it to the user. We can use
these filters with expressions and directives. A filter is usually a predefined
keyword, used with the symbol “|” (a pipe).
While explaining about Template in this article (see the template section above), I
have used an expression to display the bid amount.
<div ng-app="BiddingApp">
<input type="text" ng-model="bid" />
The expression has a text inside the curly braces {{bid}} and is prefixed with the
“$” (dollar) sign. The Angular Filter currency would spare me from using the “$”
sign. Simply add a “|” pipe after the text bid and add currency.
Advantages Disadvantages
Angular analyses the page DOM and builds multiple ways to do the same thing it is
the bindings based on the Angular-specific hard to tell which way is better for
element attributes. That requires less particular task. Mastering Angular over the
writing, the code is cleaner, easier to “Hello world” level requires considerable
understand and less error prone. efforts. Different developers‟ coding styles
solution.
Angular modifies the page DOM directly The lifecycle of Angular application is
instead of adding inner HTML code. That complex, and to master it you really need
Data binding occurs not on each control or As the project grows with time, you most
value change (no change listeners) but at likely will need to throw away existing
particular points of the JavaScript code implementations and create new versions
Quite a number of different ways to do the More than 2000 watchers can severely lag
same things, thus accommodating to the UI. That limits the complexity of your
particular development styles and tasks. Angular forms, especially big data grids
and lists.
development community.
3.1.1 app.js
This JavaScript file plays a vital role in our angularjs projects. This file is the
javascript of the application. Whenever we are starting with our application the
main important work is that the developers will have to start making their
functionalities of the project using the syntax as shown below.
Angular apps don't have a main method. Instead modules declaratively specify
how an application should be bootstrapped. There are several advantages to this
approach:
When a Controller is attached to the DOM via the ng-controller directive, Angular
will instantiate a new Controller object, using the specified Controller's
constructor function. A new child scope will be created and made available as an
injectable parameter to the Controller's constructor function as $scope.
If the controller has been attached using the controller as syntax then the
controller instance will be assigned to a property on the new scope.
Fig: Country.php
As we can see that Country Class have three parameters named name, code and state. In
the next function named construct, we are importing our parameter to this parameters.
This parameter basically points to our name, code and state of the country that we are
importing.
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
A response status code between 200 and 299 is considered a success status and will
result in the success callback being called. Note that if the response is a redirect,
XMLHttpRequest will transparently follow it, meaning that the error callback will not be
called for such responses.
The service factory function generates the single object or function that
represents the service to the rest of the application. The object or function
returned by the service is injected into any component (controller, service, filter
or directive) that specifies a dependency on the service.
Now if we recall back to our previous file that we were using $http method,
instead of it we will now use countryService to get the getCountries file.
Two-way Data Binding concept is to input and output the same values at the same time.
Here in this guide we will insert the value of a new state into a country by adding a new
textbox as shown below.
This data binding was just simply to show the process of doing the two-way binding.
Now in the next section we will see the process to enter the value into the application.
As we can see that a new function has been added to the controller. This function will
basically add a state to the country. Here also two-way data binding will take place but
the result will be stored into particular country.
Fig: StateController
Now as we have made changes in our StateController , we will simultaneously have to
make changes into our HTML file as :
From the diagram we can depict that we are creating one new directive named
“stateView” which are having different parameters namely:
Restrict: „E‟: directive is Element directive
templateUrl: Path where to view
controller: The functionality of the controller that we have to use.
controllerAs: The name of the Controller to which we are focussing.
In the above figure we can see that we have removed the part of the state Controller and
named it as <state-view></state-view> which primarily means that we are including the
state-view.html file inside that part. So whatever part that we have included in state-
view.html will be displayed in that part.
Fig: state-view.html
Fig: getStates.php
As we can see from the getStates.php file, that we are referring country repository
file so we are including the functions of getStates with parameter countryCode as
we want the results with respect to countryCode.
$routeProvider has a simple API, accepting either the when() or otherwise() method.
The when() method takes a path and a route as parameters. The path is a part of the
URL after the # symbol. The route contains two properties named templateUrl and
controller. The templateUrl property tells which HTML template AngularJS should load
and display inside the div with the ngView directive. The controller property tells which
controllers should be used with the HTML template.
When the application is loaded, the path is matched against the part of the URL after
the # symbol. If no route paths matches the given URL the browser will be redirected to
the path specified in the otherwise() function.
After taking a long consideration on the above sections we have seen the various ways of
using AngularJS. So the main part that after routing takes place in our application is as
shown below.
Fig: state-view.html
After moving to the desired path the controller part will come into action and the
functionality that have been provided will be performed. In our application this part is
getting the name of the states as per the countryCode.