Angular Js
Angular Js
</body>
</html>
Directives
• ng-init
– This directive Binds application data to HTML controls e.g.two
variables have been initialized in following html
• <div ng-app = "" ng-init = “ fname=Sara; lname=Ali”>
• ng-model
– Binds application data to control e.g. value of input field is
assigned to variable name
• <p>Enter your Name: <input type = "text" ng-model =
"name"></p>
• ng-bind
– This directive Binds the model to HTML view
• <p>Hello <span ng-bind = "name"></span>!</p>
Directives
• ng-repeat
– The ng-repeat directive actually works in iterative
manner
• <div ng-app="" ng-init=“students=[
{name:‘Ali',age:20},
{name:Ahmed',age:20},
{name:‘Sara',age:20}]">
<ul>
<li ng-repeat="x in students">
{{ x.name + ', ' + x.age}}
</li>
</ul>
</div>
Modules
• Module, in AngularJs, is container for application and
controller
• Module contains application and it’s controllers
• Application module
<script>
var app = angular.module("myApp", []);
</script>
• Controller
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = “Abc";
$scope.lastName = “Xyz";
});
</script>
Controllers
• Controller is a Javascript object
– properties and functions
<script>
Guess technique
var mainApp = angular.module(“myApp", []);
mainApp.controller(‘testController', function($scope) {
$scope.student = { firstName: “Abc", lastName: "xyz",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}); </script>
Controllers
• Use defined application and controller in
HTML
<html>
<head> <title></title>
</head>
<div ng-app = "mainApp" ng-controller = " testController ">
first name: <input type = "text" ng-model =
"student.firstName">
Enter last name: <input type = "text" ng-model =
"student.lastName">
You are entering: {{student.fullName()}}
</div>
</body>
</html>
Controllers
• $scope is a JavaScript object
• Model data is contained by $scope so in a
controller data is accessed through $scope
• Functions can be defined with $scope
Data Model
• Collection of variables for application.
• Data model belongs to a particular application
• Two way binding:
– Data is updated by getting values from html
controls
– Data id displayed by binding it with HTML controls
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model=“firstname">
<h1>You entered: {{firstname}}</h1>
</div>
• <div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>