Friday, 5 June 2015

Angular JS Expressions,Controllers and Filters


In my last article I discussed about Angular JS and its Directives. You may checked it here Introduction to Angular JS and Angular JS Directives.




How to use Expressions,Controllers and Filters in Angular JS.


Expressions:

  1. Angular JS expressions are written under {{ expression}}
  2. It bind the data same as ng-bind directive.
  3. It returns the OUTPUT exactly where the expression is written. 
Example:


<!DOCTYPE html>

<html>

<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<body>

<div ng-app="" ng-init="FName='Ashraf'; LName='Ali'">

<p>The full name is: {{ FName + " " + LName }}</p>//Expression written here

</div>

</body>
</html>


Controllers:

  1. Angular JS applications are controlled by controllers. 
  2. ng-controller directives is used to create angular applications.
Example:

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

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="FName"><br>
Last Name: <input type="text" ng-model="LName"><br>
Address: <input type="text" ng-model="Address"><br>
<br>
Full Name: {{FName + " " + LName}}
Address :{{Address}}
</div>

<script>

//Controller written here
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.FName = "Ashraf";
    $scope.LName = "Ali";
    $scope.Address="Delhi";
});
</script>

</body>
</html>

Filters:

  1. Filters are used in Angular js expression with pipe(|) character. 
Example:

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

<div ng-app="mainApp" ng-controller="studentController">
<table border="0">
<tr><td>Enter First Name:</td><td><input type="text" ng-model="student.firstName"></td></tr>
<tr><td>Enter Last Name: </td><td><input type="text" ng-model="student.lastName"></td></tr>
</table>
<br/>
<table border="0">
<tr><td>Name in Upper Case: </td><td>{{student.fullName() | uppercase}}</td></tr>
<tr><td>Name in Lower Case: </td><td>{{student.fullName() | lowercase}}</td></tr>


</table>
</div>
<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope) {
   $scope.student = {
      firstName: "Ashraf",
      lastName: "Ali",
      
      fullName: function() {
         var studentObject;
         studentObject = $scope.student;
         return studentObject.firstName + " " + studentObject.lastName;
      }
   };
});
</script>

<<PREVIOUS                                                                                    

No comments:

Post a Comment

Join US Our Community
×