top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

Understanding AngularJs: Scope, Filters, Directives, Events in HTML implementation

+1 vote
107 views

AngularJS Scope

The scope is the binding part between the HTML (view) and the JavaScript (controller). It plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object.

AngularJS

<!DOCTYPE html>

<html>

<head>

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

</script>

<script type="text/javascript" src="js/script.js"></script>

<link rel="stylesheet" href="css/style.css">

     

</head>

<body ng-app="myModule" ng-controller="myController"

ng-mousemove="coordinate($event)">

<p style="margin-left: 80%">

Coordinates: {{xCoordinate + ', ' + yCoordinate}} </p>

 

<h1 style="margin-left:50%">{{theTime}}</h1>

<p ng-click="tableShow()">

Click the table headers to change the sorting order: {{count}} </p>

<div ng-show="showMe1">

      <table border="1" width="50%" >

      <tr ng-click="count = count + 1">

      <th >ID</th>

      <th ng-click="orderByMe('name')" >Name</th>

      <th ng-click="orderByMe('country')">Country</th>

      </tr>

      <tr ng-repeat="x in names | orderBy:myOrderBy">

      <td width="5%">{{ $index + 1 }}</td>

      <td>{{x.name}}</td>

      <td>{{x.country}}</td>

      </tr>

      </table>

</div>

 

<p ng-click="ChangeCase()">Change UpperCase to LowerCase of visa-versa:</p>

<div ng-show="showMe4">

      <ul>

          <li ng-repeat="x in names"> {{x.name | myFormat}} </li>

      </ul>

</div>

 

<p ng-click="UrlPage()">The url of this page is:</p>

<div ng-show="showMe2">

      <h3>{{myUrl}}</h3>

</div>

 

<p ng-click="HedderChange()">This header will change after 3 seconds:</p>

<div ng-show="showMe3">

      <h1>{{myHeader}}</h1>

</div>

 

<div>

      <p>The hexadecimal value of 255 is: {{hex}}</p>

</div>

<div ng-click="SelectOption()">

Select an Option

      <select ng-model="selectedNames">

      <option ng-repeat="x in names" value="{{x.name}}">{{x.name}}</option>

      </select>

</div>

<h1 ng-show="showMe5">You selected: {{selectedNames}}</h1>

</body>

</html>

Script.js

var myApp=angular.module("myModule",[]).controller("myController", function($scope, $location, $http, $timeout, $interval, hexafy)

{     

      var employees=[

           {name:"Abhishek", dateOfBirth: new Date("June 9,1992"), gender:"Male", salary:20000},

           {name:"Atindra", dateOfBirth: new Date("August 9,1992"), gender:"Male", salary:21000},

           {name:"Balakrishna", dateOfBirth: new Date("March 9,1992"), gender:"Male", salary:26000}

      ];

      $scope.employees=employees;

      $scope.sortColumn="name";

      $scope.reverseSort=false;   

      $scope.sortData = function(column){

            $scope.reverseSort = ($scope.sortColumn==column)? !$scope.reverseSort:false;

            $scope.sortColumn = column;

      }

      $scope.getSortClass = function(column){

            if($scope.sortColumn==column){

                  return $scope.reverseSort ? 'arrow-down' : 'arrow-up';

            }

            return '';

      }

      $scope.count = 0;

//Sorting method

       $scope.names = [

                       {name:'Jani',country:'Norway'},

                       {name:'Carl',country:'Sweden'},

                       {name:'Margareth',country:'England'},

                       {name:'Hege',country:'Norway'},

                       {name:'Joe',country:'Denmark'},

                       {name:'Gustav',country:'Sweden'},

                       {name:'Birgit',country:'Denmark'},

                       {name:'Mary',country:'England'},

                       {name:'Kai',country:'Norway'}

                           ];

         $scope.orderByMe = function(x) {

           $scope.myOrderBy = x;

         }     

//information about the location of the current web page

         $scope.myUrl = $location.absUrl();

 //request data from the server

         $http.get("Example1.html").then(function (response) {

                  $scope.myWelcome = response.data;

              });

//The $timeout Service

         $scope.myHeader = "Hello World!";

          $timeout(function () {

              $scope.myHeader = "How are you today?";

//Create Your Own Service

          $scope.hex = hexafy.myFunc(255);

          }, 3000);

//The $interval Service

          $scope.theTime = "Welcome";

          $interval(function () {

              $scope.theTime = new Date().toLocaleTimeString();

          }, 1000);

//Counting

          $scope.count = 0;

//ShowMe or HideMe

          $scope.showMe1 = false;

          $scope.tableShow = function() {

              $scope.showMe1 = !$scope.showMe1;

          }

         

          $scope.showMe2 = false;

          $scope.UrlPage = function() {

              $scope.showMe2 = !$scope.showMe2;

          }

         

          $scope.showMe3 = false;

          $scope.HedderChange = function() {

              $scope.showMe3 = !$scope.showMe3;

          }

          $scope.showMe4 = false;

          $scope.ChangeCase = function() {

              $scope.showMe4 = !$scope.showMe4;

          }

          $scope.showMe5 = true;

          $scope.SelectOption = function() {

              $scope.showMe5 = !$scope.showMe5;

          }

//Coordinates

          $scope.coordinate = function(myE) {

              $scope.xCoordinate = myE.clientX;

              $scope.yCoordinate = myE.clientY;

          }

});

Style.css

table, th , td {

  border: 1px solid grey;

  border-collapse: collapse;

  padding: 5px;

}

table tr:nth-child(odd) {

  background-color: #f1f1f1;

}

table tr:nth-child(even) {

  background-color: #ffffff;

}

ul li{

  padding: 2px;

}

Output

posted Jul 2, 2017 by Atindra Kumar Nath

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button
Add this two AngularJS Controller inside the Script.js file, I was not able to upload in the article due to exceeding characters.


    //Custom Filters
    myApp.filter('myFormat', function() {
    return function(x) {
        var i, c, txt = "";
        for (i = 0; i < x.length; i++) {
            c = x[i];
            if (i % 2 == 0) {
                c = c.toUpperCase();
            }
            txt += c;
        }
        return txt;
    };});
    //Create Your Own Service
    myApp.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
    });


Related Articles

AngularJS

AngularJS is an open source JavaScript framework that allows to move the presentation logic on the client side and thus separate it from the logic of the application that remains on the server. AngularJS aims to minimize this complexity by offering a great environment for development, as well as the means to test your apps. 

AngularJS

Pre-request Language

  • HTML
  • CSS
  • JavaScript

Start your First HTML page with AngularJS

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

 

<!DOCTYPE html>

<Html>

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

</script>

<Body>

<div ng-app="">

  <p>Addition of 5 and 7 = {{5 + 7}} </p>

</div>

</body>

</html>

 

 

AngularJS Applications

Data Binding

Data-binding is an automatic way of updating the view whenever the model changes, as well as updating the model whenever the view changes. 

 

Controller

AngularJS controller to control the flow of data in the application. AngularJS controller is defined with ng-controller directive. AngularJS controller is a JavaScript object containing attributes/properties and functions. 

 

<!DOCTYPE html>

<html>

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

</script>

<script>

//AngularJS Module

var app = angular.module('myApp', []);

//AngularJS Controller

app.controller('myCtrl', function($scope) {

    $scope.firstName= "Atindra";

    $scope.lastName= "Nath";

});

</script>

<body>

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

      First Name: <input type="text" ng-model="firstName"><p/>

      Last Name: <input type="text" ng-model="lastName"><p/>

      Full Name: {{firstName + " " + lastName}}

      </div>

</body>

</html>

Output

Separating Controller and Module files

<html>

<head>

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

<script src="module/moduleScript.js"></script>

<script src="controller/controllerScript.js"></script>

</head>

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

      <div ng-controller="myCtrl">

      First Name: <input type="text" ng-model="firstName"><p/>

      Last Name: <input type="text" ng-model="lastName"><p/>

      Full Name: {{firstName + " " + lastName}}

      </div>

</body>

</html>

//AngularJS Module File (moduleScript.js)

var module = angular.module('myApp', []);

//AngularJS Controller (controllerScript.js)

module.controller('myCtrl', function($scope) {

    $scope.firstName= "Atindra";

    $scope.lastName= "Nath";

});

 

AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.

  • ng-app − This directive starts an AngularJS Application.
  • ng-init − This directive initializes application data.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.

ng-repeat − This directive repeats html elements for each item in a collection.

 

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

      <div>

      First Name: <input type="text" ng-model="firstName"><p/>

      Last Name: <input type="text" ng-model="lastName"><p/>

      Full Name: {{firstName + " " + lastName}}

      </div>

            <p ng-init="myCol='blue'">Write any color name

                  <input style="background-color:{{myCol}}"

                  ng-model="myCol" value="{{myCol}}">

            </p>

      <div ng-init="cost=5; quantity= [1, 15, 19, 2, 40] ;">

            <p>Total in dollar: ${{quantity [2] * cost}} </p>

      </div>

      <div>

        <ul>All Rainbow Colors

          <li ng-repeat="x in colors">

           <div style="background-color :{{ x}}; width: 10%" > {{x}} </div>

          </li>

        </ul>

      </div>

</body>

 

Output

READ MORE
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...