Hi All, Welcome to AngularJS tutorial. I have prepared this blog with my own development experience.
This blog is for those .Net developer who all are willing to learn AngularJS or want to implement AngularJS in their project.
Learn Angular JS implementation with latest and legacy ASP.Net technologies.
1. What is AngularJS?
Angular JS is JavaScript framework introduced by Google in 2012 (version 1.0). It is an open source. Angular JS allows a developer to write a powerful client-side coding. To work with Angular JS just download angular js file from https://angularjs.org and reference it into your HTML, ASPX page.
Current Stable version is 1.6.6 which was released in August 2017.
2. Why AngularJS?
AngularJS allows you to create SPA i.e. Single Page Application. AngularJS supports two-way binding. AngularJS supports dependency injections.
3. What is Two-Way-Binding?
In JQuery or JavaScript, whenever you make changes in script your HTML behavior changes for eg background changes, control values but vice-versa is not true. In Angular JS if you make changes in model it will update the view and vice-versa is also true. In below HTML code, changes in input type will make changes in the HTML page.
<div ng-app=””> <input type=”text” ng-model=”user“ /> <h1>Welcome ! {{user}}</h1> </div> |
{{}} – This is called as binding expressions.
4. What are directives in AngularJS?
Directives in AngularJs are very important. How an element will interact with its scope will be defined by directives. Directives are just an attribute on html tags with a prefix “ng-“
Below are few directives used in AngularJS
ng-app – This directive initializes AngularJS application.
ng-model- This directive binds the value HTML controls to application data.
ng-repeat- This is used to iterate application data
Other directives are ng-click, ng-show, ng-include, ng-bind-html.
We will see all of the above mentioned directives in details.
5. What is AngularJS Scope?
If you have used or seen an AngularJS code, you must have noticed $scope is the first parameter of the controller. $scope is an AngularJs object. You can say that scope is an object which binds DOM elements. $scope can access directives and other variables available within DOM. You may see a basic implementation of AngularJS with $scope in below code. Also, please observe highlighted words in below code.
HTML Code
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”binddata()“> <table> <thead> <tr> <th width=”5%”>ID</th> <th width=”15%”>Name</th> <th width=”15%”>City</th> <th width=”20%”>Department</th> </tr> </thead> <tbody> <tr ng-repeat=”dtlist in DataList“> <td width=”5%”>{{dtlist.Id}}</td> <td width=”15%”>{{dtlist.Name}}</td> <td width=”15%”>{{dtlist.City}}</td> <td width=”20%”>{{dtlist.Dept}}</td> </tr> </tbody> </table> </div> |
AngularJS Code
<script> var app = angular.module(“myApp“, []); app.controller(“myCntrl“, function ($scope, $http) { $scope.binddata = function () { var httpreq = { method: ‘POST’, url: ‘webmethod.aspx/getallempdata’, headers: { ‘Content-Type’: ‘application/json; charset=utf-8’, ‘dataType’: ‘json’ }, data: {} } $http(httpreq).success(function (response) { $scope.DataList = response.d; }) }; }); </script> |
6. What is module in AngularJS?
angular.module is a global place for creating, registering and retrieving Angular modules. It takes 2 parameters. When 2 or more parameters passed, a new module is created. If passed only one argument, an existing module (first parameter) is retrieved |
var app = angular.module(“myApp”, []); |
7. $Http in AngularJS
<script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http) { $scope.binddata = function () { var httpreq = { method: ‘POST’, url: ‘webmethod.aspx/getallempdata’, headers: { ‘Content-Type’: ‘application/json; charset=utf-8’, ‘dataType’: ‘json’ }, data: {} } $http(httpreq).success(function (response) { $scope.DataList = response.d; }) }; }); </script> |
8. What is ng-app and ng-controller in AgnularJS?
AngularJS controller define by ng-controller directive. Controller creates model for view to display data.
ng-app is the root element of AngularJS in HTML.
See below AngularJS code to create controller.
<script> var app = angular.module(“myApp”, []); var myCntrl= function ($scope) { $scope.message = “Test Message”; } //Other way to create controller in AngularJS app.controller(“myCntrl“, function ($scope) { $scope.message = “Test Message”; }); </script> <div ng-controller=”myCntrl“ ng-app=”myApp“> {{message}} </div> |
9. What are Expressions in AngularJS?
Expressions help AngularJS in data binding with HTML. Expressions in AngularJs uses double braces.
Expressions in AngularJS can be written inside a directive.
<div ng-controller=”myCntrl“ ng-app=”myApp“> Sum = {{10+20}} </div> |
10. What is ng-bind and ng-bind-html?
<div ng-controller=”myCntrl“ ng-app=”myApp“> <input type=”text” ng-model=”UserName“ /> <br /> Hello ! <label id=”l1″ ng-bind=”UserName“></label> </div> |
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”greetmessage=‘Have a good day!’“> <p ng-bind=”greetmessage“></p> </div> |
11. What is ng-model in AngularJS?
ng-model is a directive in AngularJS. ng-model is used to pass or bind the value of controls to the application data.
<div ng-controller=”myCntrl“ ng-app=”myApp“> <input name=”product” id=”txtProductName” placeholder=”Enter Product Name” class=”pname” type=”text” ng-model=”product“ /> <a href=”” ng-click=”FormSubmit()“>Click Here</a> </div> |
12. What is ng-init?
ng-init directives evaluates the expression as soon as application initialised.
For eg If you want to bind some data to HTML as soon as HTML control loads then in this condition ng-init directive is helpful.
In below implementation, product data will load as soon as application initialises.
AngularJS
<script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http) { $scope.BindProductData = function () { var httpreq = { method: ‘POST’, url: ‘mypage.aspx/BindProductData‘, headers: { ‘Content-Type’: ‘application/json; charset=utf-8’, ‘dataType’: ‘json’ }, data: {} } $http(httpreq).success(function (response) { $scope.ProductsList = response.d; }) }; }); </script> |
HTML Code
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”BindProductData()“> <div> <div ng-repeat=”productlist in ProductsList“> <div> <h2> {{productlist.Title}} </h2> <div> {{productlist.Cost}} </div> </div> <div> {{productlist.Stock}} </div> </div> </div> </div> |
13. What is ng-repeat?
ng-repeat is similar to foreach loop in C#. ng-repeat directive is use to iterate the data. Databinding is similar to gridview in asp.net. The main benefit of ng-repeat directive is, data binding can be done with any html tags.
Below code shows how to use ng-repeat directives.
<div> <div ng-repeat=”productlist in ProductsList“> <div> <h2> {{productlist.Title}} </h2> <div> {{productlist.Cost}} </div> </div> <div> {{productlist.Stock}} </div> </div> </div> |
14. nested ng-repeat
Angular JSCode <script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http) { var Brands = [ { title: “Mobile”, company: [ { title: “Nokia” }, { title: “Apple” }, { title: “Motorola” } ] }, { title: “Laptop”, company: [ { title: “Dell” }, { title: “Lenovo” }, { title: “HP” } ] }, { title: “TV”, company: [ { title: “Samsung” }, { title: “LG” }, { title: “Sony” } ] }, { title: “Digital Camera”, company: [ { title: “Nikon” }, { title: “Canon” } ] } ]; $scope.Brands = Brands; }); </script> HTML Code <div ng-controller=”myCntrl“ ng-app=”myApp“> <ul> <li ng-repeat=”brand in Brands“> {{brand.title}} <ul> <li ng-repeat=”product in brand.company“> {{product.title}} </li> </ul> </li> </ul> </div> |
15. Filter and Orderby in ng-repeat
filter and orderby clause can be used with ng-repeat directive. See below example.
<div ng-app=”” ng-init=”EmpName= Stu =[{stufname :‘John’,address:‘India’ } ,{stufname :‘Tom’,address:‘USA’ } ,{stufname :‘Sachin’,address:‘India’ }, {stufname :‘Rahul’,address:‘UK’ } ,{stufname :‘Rohan’,address:‘Australia’ } ,{stufname :‘Sunil’,address:‘India’ } ,{stufname :‘Rohit’,address:‘India’ }];”> <br /> <input type=”text” ng-model=”studentname“ /> <ol> <li ng-repeat=”s in Stu | filter: studentname | orderBy :‘stufname’ “> {{s.stufname }} </li> </ol> </div> |
16. What is trustAsHtml function in AngularJS?
The simplest way to show data in AngularJS is expression {{}}. This is ok if you have plain text. But whenever you have content with HTML tags then you must use trustAsHtml() to safe HTML data.
Let’s understand this by below implementation.
If you bind a data with AngularJs expression which contains HTML tags, it will show HTML tags with content on html page.
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”BindData()“> <div> {{HeadData}} </div> </div> |
If the server returns this data “<h1>This is a heading tag</h1>” it will print as it is on HTML page.
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”BindData()“> <div ng-bind-html=”HeadData“> </div> </div> |
To overcome all these issue, you should use trustAsHtml() function. trustAsHtml() function will be use with $sce variable
Below is the full demonstration.
AngularJS Code
<script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http, $sce) { $scope.BindData = function () { var httpreq = { method: ‘POST’, url: ‘mypage.aspx/getdata’, headers: { ‘Content-Type’: ‘application/json; charset=utf-8’, ‘dataType’: ‘json’ }, data: {} } $http(httpreq).success(function (response) { $scope.HeadData = $sce.trustAsHtml(response.d); }) }; }); </script> |
HTML Code
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”BindData()“> <div ng-bind-html=”HeadData“> </div> </div> |
Now you will get proper Output
17. Form Validation in AngularJS?
So after learning about directives in AngularJS, now we will see form validation using AngularJS.
HTML Code
<div ng-controller=”myCntrl“ ng-app=”myApp“> <form name=”form1″ novalidate> Name: <input name=”name” id=”txtName” type=”text” ng-model=”name“ required /><br /> Email: <input name=”email” id=”txtEmail” type=”email” ng-model=”email“ required /> <span ng-show=”form1.name.$dirty && form1.name.$invalid“> <span ng-show=”form1.name.$error.required“>*Name is required.</span> </span> <span ng-show=”form1.email.$dirty && form1.email.$invalid“> <span ng-show=”form1.email.$error.required“>*Email is required.</span> </span> <span ng-show=”form1.email.$error.email“>*Invalid email address.</span> <br /> <a href=”” ng-click=”SubmitForm()“>Save</a> </form> </div> |
AngularJS to Validate HTML form
<script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http, $window) { $scope.SubmitForm = function () { if (typeof ($scope.name) == “undefined” || $scope.name == “”) { $window.alert(“Name require”); return; } else if (typeof ($scope.email) == “undefined” || $scope.email == “”) { $window.alert(“Valid Email address require”); return; } var httpreq = { method: ‘POST’, url: ‘mypage.aspx/savedata’, headers: { ‘Content-Type’: ‘application/json; charset=utf-8’, ‘dataType’: ‘json’ }, data: {} } $http(httpreq).success(function (response) { alert(response.d); }) }; }); </script> |
18. How to apply Toggle CSS Class in HTML using Angular JS?
Use ng-class to toggle css class on HTML tags. See below sample code.
HTML <div ng-controller=”myCntrl“ ng-app=”myApp“> <a href=”” ng-click=”ToggleClass()“>ChangeClass</a> <div ng-class=”targetclass“ class=”headingclass”> This is a heading </div> </div> CSS <style> .headingclass { font-size:22px; font-family:‘Arial Rounded MT’; font-weight:bold; } .colorclass{ color:red; } </style> Angular JS <script> var app = angular.module(“myApp”, []); app.controller(“myCntrl”, function ($scope, $http) { $scope.targetclass = { colorclass: false }; $scope.ToggleClass = function () { $scope.targetclass.colorclass = !$scope.targetclass.colorclass; }; }); |
You may also use .toggleClass() method to do the same.
$scope.ToggleClass = function () { angular.element(document.querySelector(‘#heading’)).toggleClass(“colorclass”); }; |
19. How to add or remove a CSS class using Angular JS?
To add or remove css class using angular js, use below code
$scope.AddClass = function () { angular.element(document.querySelector(‘#heading’)).addClass(“colorclass”); }; $scope.RemoveClass = function () { angular.element(document.querySelector(‘#heading’)).removeClass(“colorclass”); }; |
Array in Angular JS
20. Array in Angular JS
Array in Angular JS is similar to Java Script.
I will write some useful Java Script method for Array which can be used in Angular JS as well.
How to define array in Angular JS ?
var color = [“Orange”, “Red”, “Blue”, “Green”]; |
Operations with an Array in Angular JS
21. pop() method in Java Script
<div ng-controller=”myCntrl“ ng-app=”myApp“ ng-init=”ShowData();”> <a href=”” ng-click=”DeleteItem()“>Delete</a> <div ng-bind=”Colors“></div> </div> $scope.ShowData = function () { var color = [“Orange”, “Red”, “Blue”, “Green”]; $scope.Colors = color; }; $scope.DeleteItem = function () { var color = [“Orange”, “Red”, “Blue”, “Green”]; color.pop(); $scope.Colors = color; }; |
22. push() method in Java Script
$scope.AddItem = function () { var color = [“Orange”, “Red”, “Blue”, “Green”]; color.push(‘Yellow’); $scope.Colors = color; }; |
23. unshift() method in Java Script
unshift() method is similar to push() method with one difference.
push() method append items in the end of an array whereas unshift() add new item as the first item in an Array. Try below Code.
$scope.UnShiftItems= function () { var color = [“Orange”, “Red”, “Blue”, “Green”]; color.unshift(‘Yellow’); $scope.Colors = color; }; |
24. shift() method in Java Script
shift() method is similar to pop()
shift() method remove items at first position.
$scope.ShiftItem = function () { var color = [“Orange”, “Red”, “Blue”, “Green”]; color.shift(); $scope.Colors = color; }; |
Above content will help you in interview preparation as well.
Please view my next blog to learn, how to insert, bind and delete data from SQL using Angular JS
http://www.sharepointcafe.net/2017/10/insert-bind-and-delete-data-from-sql-using-angularjs.html
Show Hide Div area in Angular JS
Angular JS Ng-repeat directive
Happy Learning
You may read some popular blogs on SharePointCafe.Net |
I am really impressed the way you have written the blog Thank you so much for sharing the valueable post, I appreciate your hard work.Keep blogging.
Angular JS Training in Electronic City
Angular JS 2&4 Training in Electronic City