AngularJS Service Creation

The last article provided an introduction to AngularJS services. We saw what AngularJS services are and how to use them in AngularJS applications. As an example, we implemented $location and $timeout services via controllers. In this article we shall take a step further. We shall see how to create our own custom services in AngularJS and how to hook them with controllers. Take a look at the following example.

Creating a Service

First step to AngularJS service creation is to create service function using AngularJS module. The second step is to create a method and assign it to the service.

Creating a service via module.service command is extremely simple. It is very similar to creating a controller. The first parameter to module.service is the name of the service. The second parameter is the function that the service will perform. Hooking a customized service to a controller is similar to that of built-in service. Simply pass the service as argument to the controller function. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="newApp" ng-controller="newCtrl">

    
<h1>{{display}}</h1>

</div>


<script>
var app = angular.module('newApp', []);

app.service('Message', function() {
    this.myFunc = function (str) {
        return "Welcome to knowledge hills " + str;
    }
});
app.controller('newCtrl', function($scope, Message) {
  
    $scope.name = "James";
  $scope.display = Message.myFunc($scope.name);
});
</script>

</body>
</html>

Download the code Try the code

In the above code, a service named “Messages” has been initialized. This service function “myFunc” takes one string type parameter. It then prefixes a welcome message with whatever string is passed inside the parameters. Inside the controller, $scope object is used to create a name variable. This variable is passed to the myFunc method of the service. Therefore, whatever is stored in this variable, it gets printed on the screen with a welcome message.

Creating A Sum Service

Now, since we know how to create a service in AngularJS, in the next example we have created a more advanced service in AngularJS. This service takes two numbers and returns their sum. Take a look at the following code.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="newApp" ng-controller="newCtrl">

    
<h1>{{sum}}</h1>

</div>


<script>
var app = angular.module('newApp', []);

app.service('Sum', function() {
    this.myFunc = function (x,y) {
        return x + y;
    }
});
app.controller('newCtrl', function($scope, Sum) {
  
    $scope.num1 = 10;
    $scope.num2 = 20;
  $scope.sum = Sum.myFunc($scope.num1, $scope.num2);
});
</script>

</body>
</html>

Download the code Try the code

In the above code a service named “Sum” has been initialized via module.service function. This service has one function myFunc. It takes two parameters, adds them and return the sum. This service is hooked to “newCtrl” controller. Inside the controller the $scope object creates two variables. They are assigned values of 10, 20. These variables are passed to myFunc method of the service. The returned value is stored in $scope.sum object which is displayed in the view.

AngularJS Services

AngularJS is a very comprehensive framework. It comes with a tool set that can be used to perform almost all the client side functionalities. One of the most amazing features of AngularJS is the Angular services. AngularJS services are basically functions that perform particular tasks. AngularJS fosters separation of concerns via Services. Both controllers as well as filters can call AngularJS services. There are a total of about 30 AngularJS services. $route, $window, $http, $location are some of them. Services are limited to AngularJS application in which it is created. Let’s have a look at a very simple example of AngularJS services.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="newApp" ng-controller="newCtrl">
<p>The Absolute url of this page is:</p>
<h1>{{absUrl}}</h1>
</div>



<script>
var myapp = angular.module('newApp', []);
myapp.controller('newCtrl', function($scope, $location) {
    $scope.absUrl = $location.absUrl();
});
</script>

</body>
</html>

Download the code Try the code

Open the above page in the browser. You should see absolute URL of the page in h1 heading. Now take a close look at the script section inside the code. Here we are passing the “$location” parameter to the controller function. To use a built-in service inside a controller, you have to pass it as a parameter to the controller function. Next inside the controller we create a variable that stores the absolute URL of the current page. To get the absolute URL, simply call absUrl() function the $location service.

Timeout Service

Timeout service is another extremely useful AngularJS service. $Timeout service can be used to update model data at any time. Take a look at the following example to see what $timeout service does.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="newApp" ng-controller="newCtrl">

<p>Header text will change in three seconds:</p>

<h1>{{newHeader}}</h1>

</div>


<script>
var timerapp = angular.module('newApp', []);
timerapp.controller('newCtrl', function($scope, $timeout) {
  $scope.newHeader = "Knowledge hills!";
  $timeout(function () {
      $scope.newHeader = "Best tutorial site!";
  }, 3000);
});
</script>

</body>
</html>

Download the code Try the code

Open the above page in the browser. You will see an h1 heading with some random text. Now wait for three seconds. After three seconds the text in the heading will change. Have a close look at the code. In the script section, we pass the $timeout service to a controller. The $timeout service further takes two parameters. The first one is the function to execute. And the second parameter is time in milliseconds after which the function executes.Therefore when you open the page, the value of the header changes after three seconds.

Next article explains the process of creating custom services. Happy coding!

AngularJS Filters

You can modify the data stored in application variables via AngularJS filters. Pipe character is used to add a filter to any expression. Following are the most frequently used AngularJS filters.

  • Uppercase
  • Lowercase
  • Currency
  • Filter
  • OrderyBy

Let’s have a look at each of the aforementioned AngularJS filters in detail

Uppercase and Lowercase

These filters change the case of a string. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	<p>Car Name: <input type="text" ng-model="carname"></p>
    
 	<p ng-bind="carname | uppercase"></p>
    <p ng-bind="carname | lowercase"></p>
</div>

</body>
</html>

Download the code Try the code

Open the above page in the browser. You should see a text box. Type anything in the text box. The text you entered shall appear twice below the text box in upper as well as in lower case. Now take a look at your code. We have an application variable “carname” bound to input of text box. Next, we have two paragraphs. In the first paragraph we use ng-bing directive to bind “carname” variable to inner html of the paragraph. Inside the ng-bind directive we mentioned application variable followed by pipe character and the filter i.e. “uppercase”. Similarly, in the next paragraph we used the “lowercase” filter to change the case of the paragraph to lowercase.

Currency Filter

Currency filters prefix currency symbol with the number type data. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	<p>Car Price: <input type="text" ng-model="carprice"></p>
    
 	{{carprice | currency}}
</div>

</body>
</html>

Download the code Try the code

Now, if you open the above page in browser, you should see a text box. Start entering number values in the text box. You shall see the numbers with currency symbol prefixed in the paragraph below the text box. If you enter characters, you shall see that the text disappears. This is because we have used currency symbol and the paragraph accepts a number.

Filter Filters

Filter filters are only applicable on arrays. They are used to filter array elements based upon a specified criteria. Take a look at the following example to understand these filters.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="colors=['red','green','blue','yellow']">
 	
    <ul>
      <li ng-repeat="x in colors | filter : 'l'">
        {{ x }}
      </li>
    </ul>
    
</div>
    

</body>
</html>

Download the code Try the code

The above filter will filter all the colors with letter “l” from the colors array.

Order By Filter

You can use order by operator to arrange items in ascending order. In the following example the orderBy filter sorts the items in the color array in alphabetical order. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="colors=['red','green','blue','yellow']">
 	
    <ul>
      <li ng-repeat="x in colors | orderBy:'toString()'">
        {{ x }}
      </li>
    </ul>
    
</div>
    

</body>
</html>

Download the code Try the code

AngularJS Scopes

In the last few articles we have been discussing controllers, models and views. Since AngularJS is based on MVC architecture, the responsibility of controllers is to bind data between a model and a view. As discussed earlier, model part of MVC stores all of the application data. There are three ways to initialize a data model: via “ng-init”, via “ng-mode” and via $scope object inside the controller. We have seen the first two methods in detail in the previous article. This article explains AngularJS scopes in detail.

$Scope is an AngularJS object used for biding between JavaScript controller and HTML view. It is available in both controller as well the view. $Scope contains methods and properties like any other object. Whenever you create a new controller, you pass $scope as parameter. Inside the controller you can create model via the $scope object. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>
    
          <div ng-app="newApp" ng-controller="newCtrl">

        <h3>{{student}}</h3>

        </div>

        <script>
        var app = angular.module('newApp', []);

        app.controller('newCtrl', function($scope) {
            $scope.student = "Michel";
        });
        </script>

</body>
</html>

Download the code Try the code

Take a look at the above code. It might look familiar to you. However, I will explain this code from the perspective of scope this time. The above script contains a controller “newCtrl”. Inside the controller we creaate a new string variable “student” and assign it some value. Now, come to the div section which contains the view. Since, this view is bound to ‘newCtrl’ controller, therefore all the values in the $scope of this controller are accessible here. Therefore in h3 headings, we displayed the value of “student” variable via AngularJS expression.

Scope Inheritance

AngularJS Scopes are inheritable. For instance if we have nested scopes the child scope will automatically inherit the scope of the parent. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>
    
     <div ng-app = "VehicleApp" ng-controller = "VehicleController">
         <p>{{text}} <br/> {{type}} </p>
         
         <div ng-controller = "CarController">
            <p>{{text}} <br/> {{type}} </p>
         </div>
         
         <div ng-controller = "BikeController">
            <p>{{text}} <br/> {{type}} </p>
         </div>
			
      </div>
		
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      
      <script>
         var mainApp = angular.module("VehicleApp", []);
         
         mainApp.controller("VehicleController", function($scope) {
            $scope.text = "This is vehcicle Controller";
            $scope.type = "Vehicle";
         });
         
         mainApp.controller("CarController", function($scope) {
            $scope.text = "This is car controller";
         });
         
         mainApp.controller("BikeController", function($scope) {
            $scope.text = "this is bike controller";
            $scope.type = "Bike";
         });
			
      </script>

</body>
</html>

Download the code Try the code

Take a look at the script section of the above code. Here we have three controllers: Vehicle, Car and Bike. The vehicle controller has two variables in its model i.e. text and type. Car has one variable text. Bike again has two variables text and type. Now come to the view section. Here the “VehicleController” is bound to the outer div. “CarController” and “BikeController” has been nested inside the “VehicleController”. Now, if you display “text” and type outside the nested controller, the text and type of VehicleController will be printed. However, if you display the text and type inside the “CarController”, its text will be printed, but type variable will contain value of the outer “VehicleController”. This is because “CarController” only overrides the “text” variable. It inherits the “type” variable from the parent controller.

AngularJS Models

In the previous article we studied controller in detail. In this part, we shall study another important concept i.e. AngularJS Models. In simplest words, AngularJS allows you to bind the input of an html element to an application variable. This application variable can be created via ng-init or via $scope object inside the controller function. The ng-model directive binds the inner html of the element to AngularJS application variable. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	<p>Car Name: <input type="text" ng-model="carname"></p>
 	<p ng-bind="carname"></p>
</div>

</body>
</html>

Download the code Try the code

Open the above page in a browser. It contains a text field and some text underneath. Start typing something in the text box. The same text shall appear below the text field. This happens because the “ng-model” binds the input of textbox to application variable “carname”. Similarly, AngularJS expression binds the value of this variable to inner html of the paragraph. Therefore, whenever you update the value in textbox, the value in paragraph also changes accordingly.

Input Validation via AngularJS Models

AngularJS models can also validate user inputs. For instance if you want to validate whether a user has entered valid email or not, you can do so via AngularJS models. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<form ng-app="" name="newform">
    Email:
    <input type="email" name="myemail" ng-model="text">
    <p ng-show="newform.myemail.$error.email">Please enter valid email </p>

</form>
        

</body>
</html>

Download the code Try the code

The above code contains a text box which accepts email. Until you enter correct email, the message “please enter correct email” will remain in display.

Another way to implement validations in via model is via css classes. For instance you may want that unless a user enters something in a textbox, the color of the text box should remain pink. As soon as the user enters some text, the color should change to default. This can be easily implemented via AngularJS models and css validation classes. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    
    <style>
    input.ng-invalid {
        background-color: pink;
    }
    </style>
    
</head>
    
<body>
    
    <form ng-app="" name="newForm">
        Enter your name:
        <input name="carname" ng-model="carText" required>
    </form>
</body>
</html>

Download the code Try the code

Open the above page in browser. You should see a text box with pink background by default. Enter something in the text box. It’s background color will change to default. Again empty the text box, the color of the text box will again change pink. This is because in styles we have set the color of the “ng-invalid” class for input elements to “pink”. Next, we have added required attribute to our text box. Therefore the input in the text box will remain invalid until it is empty. Therefore, the background color of the text box will remain pink. As soon as you enter something in the text box, the input will become valid. Therefore, “ng-invalid” class will be removed from the text box and is background color will change to default.

AngularJS Controllers

In the articles on MVC, we briefly reviewed what MVC pattern is and how AngularJS implements it via model, views and controllers. In this article, we are going to study AngularJS controllers in detail. Simply put, AngularJS controller controls the flow of data in the application. Angular.js Controllers are responsible for interaction between models and views. AngularJS controllers are nothing but simple JavaScript objects. These objects contain attributes and functions. A controller accepts $scope variable as a parameter. This variable defines the scope of the module or application that the controller will handle.

Declaring AngularJS Controllers

AngularJS controllers are declared via “ng-controller” directive. Similarly, to define a controller, you have to create controller object via JavaScript. Take a look at the following example. The code has been explained in the following section.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

           
      <div ng-app = "SumApp" ng-controller = "SumController">
         First Number: <input type = "text" ng-model = "Sum.num1"><br><br>
         Second Number: <input type = "text" ng-model = "Sum.num2"><br>
         <br>
         
         Sum of Numbers: {{Sum.TotalSum()}}
      </div>
      
      <script>
         var mainApp = angular.module("SumApp", []);
         
         mainApp.controller('SumController', function($scope) {
            $scope.Sum = {
               num1: 10,
               num2: 30,
               
               TotalSum: function() {
                  var SumObject;
                  SumObject = $scope.Sum;
                  return SumObject.num1 + SumObject.num2;
               }
            };
         });
      </script>  
    
    
</body>
</html>

Download the code Try the code

Now pay close attention to the above code, we shall start from the div with attribute “ng-app”. In all the past articles, we didn’t enter value for this attribute. However, in the above code “ng-app” has a value “SumApp”. This is the name of the module. We shall see more about modules in upcoming articles. For now, just keep in mind that modules are containers for AngularJS application. If you want to create multiple AngularJS applications within one webpage, you can use multiple modules.

Next, using “ng-controller” directive, we have declared a “SumController“. This means that inside this div, we can use models defined inside the SumController object.

Now, leave the rest of the code inside the div and come straight down to the script section. Here we create a controller object named “SumController“. Inside this controller, we create Sum object via “$scope” variable. The sum object has two variables, num1 and num2; and a function “TotalSum” which returns the sum of num1 and num2 variables.

We have created our controller and model. Now is the time to bind the model with the view. Go back to the div where we declared controller. Here we have bound two text boxes with num1 and num2 variables of sum object. Similarly, using an expression, we bound the inner html of the body to the output of “TotalSum” function of the model. Now, enter random numbers int the text boxes. The sum will be updated at run time.

AngularJS Data Types

In the last article we covered AngularJS expressions. We saw how AngularJS evaluates an expression and returns results. In this article we shall study AngularJS data types that are used to store different types of data.

There are four major AngularJS data types.

  • Numbers
  • Strings
  • Arrays
  • Objects

In the following sections, we shall see how to declare each of the above data types and how to store values in these data types.

AngularJS Number Variables

Angular JS numbers variables are created by simply storing a number in AngularJS variable. Take a look at the following example to see how AngularJS creates number variables.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="num1=10;num2=3">

    
Number1 multiplied by Number2: {{ num1 * num2 }}
<p ng-bind="num1 * num2"></p>


</div>

</body>
</html>

Download the code Try the code

In the above code, if you look at the “ng-init” directive, you should see that it contains two number type variables num1 and num2. Next, expression as well as “ng-bind” directive is displaying the product of these two variables.

AngularJS String Variables

To declare a string variable in AngularJS, simply assign some value withing quotes to a variable. Take a look at the followin example to see how string variables are declared in AngularJS.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="fname='Eric';lname='Cantona'">

    
{{fname +" "+lname}}
<p ng-bind="fname +' '+lname"></p>


</div>

</body>
</html>

Download the code Try the code

In the above code, the “ng-init” directive initializes two string variables “fname” and “lname”. It is important to note here that to semi-colon separates one variable from the other inside “ng-init”.

AngularJS Arrays

AngularJS arrays store collection of data. It is very easy to declare arrays in AngularJS, have a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="colors=['red','green','blue','yellow']">

<p>The second color in the list is {{ colors[1] }}</p>
<p>The second color in the list is <span ng-bind="colors[1]"></span></p>

</div>

</body>
</html>

Download the code Try the code

In the above code, the “ng-init” directive initializes a string array named colors. The array contains names of four colors. Next, the expression and ng-bind directive, both are used to display the second item in the array. However, it is important to note that AngularJS arrays store first item at 0th index.

AngularJS Objects

AngularJS objects are similar to objects in JavaScript. Take a look at the following example to see how to initialize and access objects in AngularJS.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="result={mathematics:'passed',english:'fail'}">

<p>Result for mathematic is : {{ result.mathematics }}</p>

</div>

</body>
</html>

Download the code Try the code

AngularJS MVC

MVC is one of the most advanced and popular web development frameworks. MVC stands for model, view and controller which are basically three components of the framework. Let’s briefly explain these components. After that we shall see how AngularJS MVC works.

Model

The model component of MVC architecture is responsible for storing all the application data. For instance, if you are developing a database application, all the interaction with the database will be done via Model component. Also, storage of in-memory data is also the responsibility of the model. In short, all the application data is stored in models.

View

View are responsible for creating user views or front ends of the application. Everything you see on a webpage is actually generated via views.

Controller

Controller is a backbone of MVC architecture. It is responsible for processing user requests, saving data to the model and passing model to the views. Basically it acts as a moderator between views and models.

MVC architecture fosters separation of concerns. Each component in MVC performs its own functionality. This results in loose coupling where you can easily update one part of the application without disturbing the other.

AngularJS MVC Example

We have been saying that AngularJS is based upon MVC architecture. Let us see a simple example to understand how AngularJS exploits MVC.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>

    <body ng-app = "subjectapp">
      
  <!--  this connects view with controller function-->
      <div ng-controller = "SubjectController" >
         <h1>You {{Subject.Mathematics}} in Mathematics</h1>
      </div>
      
        
    <!--this is where model is created inside controller-->
      <script>
         angular.module("subjectapp", [])
         
         .controller("SubjectController", function($scope) {
            $scope.Subject = {};
            $scope.Subject.Mathematics = "Passed";
         });
      </script>
      
   </body>
    
</html>

Download the code Try the code

Have a look at the above code. First, go to the script section in the end of the body tag. This is where controller module, controller function the model is created. Here the controller function is the “SubjectController”, and to this function $scope object is passed. The $scope object is used to create Model in AngularJS. In above example a model named “Subject” has been created. Inside the model a variable “Mathematics” has been initialized with a value of “Passed”.

Now to bind your view to the model, you have to wrap view within an element with attribute “ng-controller”. The value for “ng-controller” should be the controller function which has the model which is to be displayed by the view. Since, the view we have displays the value for “Subject” model which is inside the “SubjectController” function, so the value of “ng-controller” will be “SubjectController”. To access the value of the variable within the model in view, use double opening and closing parenthesis. Within the parenthesis write the name of he model followed by dot operator and the variable name e.g {{Subject.Mathematics}}. This is how AngularJS MVC works.

AngularJS Environment Setup

In the previous article we introduced AngularJS. In this article contains brief information about AngularJS environment setup. We shall explain how you can can turn a normal HTML application into an AngularJS application. We shall also explain basic components of an AngularJS application. In this article, we shall do some real coding, so let the fun begin!

Environment Setup

AngularJS is a JavaScript library, the best way to use AngularJS in your applications is by adding CDN referent to AngularJS library hosted by google. Take a look at the following code sample to see how AngularJS CDN is included in an application, so that it can use AngularJS.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	<p>Car Name: <input type="text" ng-model="carname"></p>
 	<p ng-bind="carname"></p>
</div>

</body>
</html>

Download the code Try the code

Take a look a the above code. In the head section, you should find a JavaScript reference that points to AngularJS library hosted by google. Now to see if AngularJS is actually working, open the above page in the browser. You should see a text box. Start entering anything in the text box. You will see that as soon as you start entering text in the text box, same text appears below it. Changing the characters in the text box, updates the text below it at run time.

This is something really cool. To achieve such functionality in JavaScript, you would have to create a function that would have to be called on every key pressed. This shows the power of AngularJS while performing tasks that would otherwise require large and complex piece of code.

If you look at the code above, you should see three attributes ng-app, ng-model, ng-bind. These are basically AngularJS directives. AngularJS Directives are attributes that extend HTML elements to include AngularJS functionalities. We shall study AngularJS directives in more detail in an upcoming article. For now just breifly explain what these three directives do.

  • ng-app:This attribute says that the AngularJS functionalities would exist only within this element.
  • ng-model:¬† The ng-model directive binds an input , select , textarea (or custom form control) to a property (application variable) on the scope. In the above case “carname” is AngularJS application variable and it is bound to a text box.
  • ng-bind:It binds the value of application variable to inner html of any html element.

In this article we studied AngularJS Environment Setup. In the next article, we shall how what MVC architecture is and how AngularJS makes use of it.

AngularJS Expressions

Last article explained AngularJS directives in detail. This article focuses on AngularJS Expressions. In AngularJS, expressions are written inside double curly opening and closing brackets i.e. {{expression}}. You can also write an expression in AngularJS inside the “ng-bind” directive i.e. ng-bind=”expression”. Anything in the expression is evaluated by AngularJS which returns the result of the expression. Expressions in AngularJS are quite similar to JavaScript expressions. You can use literal values, operators and variables inside expressions. Take a look at our first example of AngularJS expressions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
    <p>{{3 *5}}</p>
 	<p ng-bind="3*5"></p>
    
</div>

</body>
</html>

Download the code Try the code

In the above example both ng-bind and doubly curly brackets contain an expression which multiplies 3 and 5. If you open the above webpage in browser, you will see 15 displayed twice in the output.

Now if you try to remove the “ng-app” attribute from the div, and then execute AngularJS expression inside the div, you will see that the page shall display “{{3 * 5}}”.

Changing Style Via AngularJS Expressions

AngularJS expressions can change script as well as style associated with any html element. Take a look at the following example to see how to change text color of a paragraph via AngularJS expressions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="textcolor='pink'">

<input type="text" ng-model="textcolor">

<p style="color:{{textcolor}}">The color of this text changes as specified in text box.</p>

</div>

</body>
</html>

Download the code Try the code

Open the above page in the browser. You will see a text box with text “pink”. Below the text box there should be paragraph with pink text. Now change the text inside the paragraph from pink to blue. You will see the color of the text inside the paragraph turn blue. This is because we initialized an AngularJS variable “textcolor” and assigned it value of color. Then using ng-model this application variable was bound to the input value of the text box. Finally, for the paragraph style, we specified that its color should be equal to the value of the AngularJS application variable “textcolor”. Therefore, changing the color name in the text box updated the text color of the paragraph.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .