Tutorial 2 - ng-controller in AngularJS

In AngularJS, an applications are controlled by controllers.
The ng-controller directive defines the application controller.
One ng-app have one more ng-controller

How to define a controller Javascript?



 <script>  
 var app = angular.module('myWebApp', []);app.controller('studentCtrl', function($scope) {  
 $scope.firstName = "Huynh";    
 $scope.lastName = "Hai";    
 $scope.fullName = function() { return $scope.firstName + " " + $scope.lastName;  }});  
 app.controller('classCtrl', function($scope) {  $scope.ClassName= "K2T3";  }});  
  </script>  


How to use the controller?
 <div ng-app="myWebApp" ng-controller="studentCtrl">  
    First Name: <input type="text" ng-model="firstName">  
    <br>  
    Last Name: <input type="text" ng-model="lastName">  
    <br>
    Student Full Name is {{firstName + " " + lastName}}  
 </div>  
 <div ng-app="myWebApp" ng-controller="classCtrl">  
     <p>Class: {{ClassName}}</p>  
 </div>  

Notes: above sample using two controllers studentCtrl and  classCtrl in a ng-app



No comments:

Post a Comment

Popular Posts