Hands-on AngularJS: Directives, Models, Controllers
In the previous part of Hands-on AngularJS, I talked about the basics and architecture of AngularJS, plus a few directives. In this post, we'll check out important directives and go into more detail about Angular interaction with Controller and Model. Read on to learn more.
Join the DZone community and get the full member experience.
Join For FreeIn the previous part of Hands on Angular Js-I, I talked about the basics and architecture of Angular JS, plus a few directives. In this part, we will check out the other important directives and how Angular interaction with Controller and Model is being done on the go. The directives we will discuss in this part of the series are very important in order to understand the magic of Angular. Here, we get into the depth and controls of Angular. Let’s check it out.
Angular Directives
Let's start with the important directives that wwill come in handy while working with Angular.
ng-module
Angular modules are the most important directive, they define an angular application. They are the parent set for the other directives or functions of the application, like controllers. Controllers are always contained within the modules, along with other dependencies. This is the modular approach in Angular. Creating modules for separate section segregates it and creates partition/module wise applications.
The modules are defined syntactically as below:
var app = angular.module("app-Services", []);
As per the above snippet, we have created an angular module and assigned it to the variable named app. The module name is app-Services. The module is actually defined in the document function of a separate Module script file and reference added to the file wherever required. The definition provided by the Angular Doc is that Module is required to configure the $injector and it contains the services, directives, controllers, and other dependencies.
$injector is the service used to retrieve the pre-defined object instances, invoke methods, and load the required modules.
ng-controller
This is another set of directives that defines the controller of the application, which controls the data of the application. They are simple objects defined under the scope of the module. There can be any number of controllers for a specific module. Controllers are defined syntactically as:
var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
$scope.firstName = "Suraj";
$scope.lastName = "Sahoo";
});
The above snippet is a simple controller defined under the module app-Services. The name of the controller is myFirstController and under its scope, two members are initialized, that is firstName & lastName. Thus, an object of a controller is created in the html, which we will see below:
<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName}} {{ctrlFirst.lastName}}</span>
</div>
</body>
</html>
As we see above, the html tag div has the scope for the Module we defined above and the controller defined for the module with the members firstName & lastName. When the controller is instantiated inside the scope of the div and Module, we have the right to access the data defined inside the controller function. $scope defined within the controller function is the context via which the model execution is implemented inside the controller. It actually acts as a watch on the model values while binding to the DOM element in the HTML. The $scope can also be used by using the this object. The controller also accepts the $http to execute the http services in order to call the APIs to get, post, and delete any data through the services. Lets see how the controller function can be separated from the declaration and defined as a function.
var app = angular.module('app-Services', []);
app.controller('myFirstController', myFirstController);
function myFirstController($http, $scope) {
$scope.firstProperty = 'XYZ';
$http.get('your url').then(function (){
//do whatever..
}).catch(function (){
//do whatever..
}).finally(function (){
//do whatever..
});
}
});
Now, the above $http is the http module which is used to call the get and post methods or to interact with the server to fetch the records. Call the URL, just like in AJAX how we have success and error methods, here we have the then() block, which after fetching a successful response, has the logic about what to do next. Actually, the $http returns a promise, so we catch that in the then block and attach the response to the scope. The different $hhtp methods are:
- $http.get: To retrieve information from server for a URL requested by the user
- $http.head: Transfers only the header and the status line only, but is same as GET
- $http.post: As self explanatory it is, it is used to send the information entered by user to the server
- $http.put: This is the same as the POST but is used to create the current reprsentation of the target resource or overwrite it for the same URL
- $http.delete: This ensures that the current resource for the requested URL is deleted by the server.
The catch finally is the same as the try... catch... blocks, where inside the catch we can also have the "then" block in order to perform tasks after catch and similarly the "finally" block to ensure what the code block will finally execute.
Filters in Angular JS
These are very interesting features provided by Angular, which can be frequently used and with ease. Below we will discuss the pre-defined filters provided by the framework. We will see the use syntactically after the line by line explanation.
- currency: This is used as the name suggests, to convert a simple number into the format of a currency
- date: this is used to format dates in different formats
- filter: an interesting filter which actually filters some data from a set of result set data
- json: formats a normal object into JSON format
- limitTo: limits a set of array to specified number of elements or objects
- lowercase: converts/formats a string to a lower case character
- number: formats a simple number into a string
- orderby: Orders an array based on an expression
- uppercase: Formats the string into an upper case character
Let's see the work around using the snippets:
var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
$scope.firstName = "Suraj";
$scope.lastName = "Sahoo";
});
<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName | uppercase}} {{ctrlFirst.lastName \ lowercase}}</span> //Displays firstName is UPPERCASE and lastName in lowercase
<ul>
<li ng-repeat="name in names | orderBy:'age'">
{{ x.name + ', ' + x.age}}
</li>
</ul>
<span>{{price | currency}}</span>
<li ng-repeat="name in names | filter : 'S'">
{{ name }} //Filters names based on names containing 'S'
</li>
</div>
</body>
</html>
In the above snippets, we have used another directive (ng-repeat) that is used to loop through the list of records just like for each loop.
Another thing to note here is that the filter used in the above snippet, if we use the object containing the data or list of records/names, is supposed to look like:
<p><input type="text" ng-model="nameFilter"></p>
<ul>
<li ng-repeat="name in names | filter:nameFilter">
{{ name }}
</li>
</ul>
The above snippet loops through the names and, based on the entry in the textbox or the user input, filters to a specific letter. For instance, suppose a user enters "S", then the data listed is filtered on the objects with names that start with "S". Thus, we can see how these filters become handy.
Conclusion
In this part we discussed many of the great features of Angular and saw a few snippets to be used in progress. As I said earlier, in the succeeding modules we will gradually come across more interesting features and overall use of Angular.
Whats Next?
We will next come across how to build applications using Asp.NET MVC, EF Code First, and Angular JS. This I assure you will be interesting.
Published at DZone with permission of Suraj Sahoo, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments