CodesJava

Easy learning with example program codes

AngularJs controller tutorial


AngularJs controller:

AngularJS controllers are used to control the data and flow of AngularJS applications. The ng-controller directive is used to define the AngularJS controller. AngularJS controllers are JavaScript Objects containing attributes or properties and functions. Each AngularJS controller accepts $scope as a parameter which refers to the application or module which is to be controlled by controller.

Syntax:

<div ng-app = "" ng-controller = "controllerName">
   ...
</div>

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. The ng-model directive binds the state of the input text to the respective name variables (student.firstName and student.lastname). The ng-controller=”appController” directive defines the controller. The appController defined as a JavaScript object with $scope as argument. The $scope.student is property of appController object. In $scope.student.fullName we are getting the combined name (firstName + lastName).
 
Note: We can also store controllers in external files .JS file and refer that file in the html page.

Example:

<html>
 
   <head>
    <title>Angular Controller Example</title>
    <script src = 
     "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
    </script>
   </head>
 
   <body>
      <h2>AngularJS Controller Example</h2>
 
      <div ng-app = "testApp" ng-controller = "appController">
         Enter first name: 
         <input type = "text" ng-model = "student.firstName">
         <br><br>
         Enter last name: 
         <input type = "text" ng-model = "student.lastName">
         <br><br>
 
        Entered Value: {{student.fullName()}}
      </div>
 
      <script>
         var mainApp = angular.module("testApp", []);
 
         mainApp.controller('appController', function($scope) {
            $scope.student = {
               firstName: "Vivek",
               lastName: "Solenki",
 
               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " "
                                + studentObject.lastName;
               }
            };
         });
      </script>
 
   </body>
</html>

Try it:

Angular Controller Example on jsbin.com
 



Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki