Angular JS Programming
Angular JS Programming
Introduction to Angular JS
programming
Angular JS Modules:
Mr.D.Prasanth
Functions & Modules
myApp.js
Mr.D.Prasanth
Week 2 myCtrl.js, Angular JS Controllers,
Assignment-2
Controller Methods
Angular JS Forms
Week 3
Mr.D.Prasanth
Data-Binding, Checkbox
Angular JS $http
MODULE -2
Durations Topics Resource Person
Angular JS Example
Creating a Chart
The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
The ng-bind directive binds application data to the HTML view. Angular JSExample
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/Angular JS/1.4.8/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Example explained:
The ng-app directive tells Angular JS that the <div> element is the "owner" ofan Angular JS
application.
The ng-model directive binds the value of the input field to the applicationvariable name.
The ng-bind directive binds the inner HTML of the <p> element to theapplication
variable name.
Directives
Angular JS Modules
<div ng-app="myApp">...</div>
<script>
</script>
The "myApp" parameter refers to an HTML element in which the application willrun.
Now you can add controllers, directives, filters, and more, to your Angular JSapplication.
Adding a Controller
Add a controller to your application, and refer to the controller with the ng-controller
directive:
Example
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + last Name }}
</div>
<script>
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
Adding a Directive
Angular JS has a set of built-in directives which you can use to add functionalityto your
application.
In addition you can use the module to add your own directives to yourapplications:
Example
<script>
var app = angular.module("myApp", []);
</script>
Modules and Controllers in Files
It is common in Angular JS applications to put the module and the controllers inJavaScript
files.
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/Angular JS/1.4.8/angular.min.js"></script>
<body>
</body>
</html>
myApp.js
Without the [] parameter, you are not creating a new module, but retrieving anexisting one.
myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
Functions can Pollute the Global Namespace
Global functions should be avoided in JavaScript. They can easily be overwrittenor destroyed by
other scripts.
Angular JS modules reduces this problem, by keeping all functions local to themodule .
When to Load the Library
This is because calls to angular.modulecan only be compiled after the libraryhas been loaded.
Example
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/Angular JS/1.4.8/angular.min
.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Angular JS Controllers
Angular JS Example
<div ng-app="myApp" ng-controller="myCtrl">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
Application
The controller creates two properties (variables) in the scope (firstName and
lastName).
The ng-model directives bind the input fields to the controller properties(firstName and
lastName).
Controller Methods
The example above demonstrated a controller object with two properties:lastName and
firstName.
Angular JS Example
<div ng-app="myApp" ng-controller="personCtrl">
</div>
<script>
var app = angular.module('myApp', []); app.controller('personCtrl',
function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
Just copy the code between the <script> tags into an external file named
personController.js:
Angular JS Example
<div ng-app="myApp" ng-controller="personCtrl">
</div>
<script src="personController.js"></script>
Another Example
Angular JS Example
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script src="namesController.js"></script>
Angular JS Forms
Input Controls
input elements
select elements
button elements
textarea elements
Data-Binding
The ng-modeldirective binds the input controller to the rest of your application.The property
firstname, can be referred to in a controller:
Example
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
It can also be referred to elsewhere in the application:
Example
<form>
First Name: <input type="text" ng-model="firstname">
</form>
Checkbox
A checkbox has the value trueor false. Apply the ng-modeldirective to acheckbox, and use its
value in your application.
Example
Show the header if the checkbox is checked:
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
Radiobuttons
Radio buttons with the same ng-modelcan have different values, but only theselected one will be
used.
Example
Display some text, based on the value of the selected radio button:
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
Selectbox
The property defined in the ng-modelattribute will have the value of theselected option in the
selectbox.
Example
Display some text, based on the value of the selected option <form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
</form>
Last Name:
RESET
Application Code
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>Last
Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
Example Explained
The ng-model directive binds two input elements to the user object in themodel.
The formCtrl controller sets initial values to the master object, and defines the
reset() method.
The reset() method sets the user object equal to the master object.
The ng-click directive invokes the reset() method, only if the button is clicked.
The novalidate attribute is not needed for this application, but normally you willuse it in
Angular JS forms, to override standard HTML5 validation.
Angular JS AJAX - $http
http://www.w3schools.com/angular/angular_http.asp
Angular JS $http
The Angular JS $httpservice makes a request to the server, and returns aresponse.
Example
Make a simple request to the server, and display the result in a header:
</div>
<script>
var app = angular.module('myApp', []); app.controller('myCtrl',
function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
Methods
The .get method is a shortcut method of the $http service. There are severalshortcut
methods:
.delete()
.get()
.head()
.jsonp()
.patch()
.post()
.put()
The methods above are all shortcuts of calling the $http service:
Example
var app = angular.module('myApp', []); app.controller('myCtrl',
function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
The example above executes the $http service with an object as an argument.The object is
specifying the HTTP method, the url, what to do on success, andwhat to do on failure.
Properties
Example
var app = angular.module('myApp', []); app.controller('myCtrl',
function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope. Content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
});
});
Example
var app = angular.module('myApp', []); app.controller('myCtrl',
function($scope, $http) {
$http.get("wrongfilename.htm")
.then(function(response) {
//First function handles success
$scope.content = response.data;
}, function(response) {
//Second function handles error
$scope.content = "Something went wrong";
});
});
JSON
The data you get from the response is expected to be in JSON format.
JSON is a great way of transporting data, and it is easy to use within Angular JS,or any other
JavaScript.
Example: On the server we have a file that returns a JSON object containing 15customers, all
wrapped in array called records.
Example
The ng-repeat directive is perfect for looping through an array:
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []); app.controller('customersCtrl',
function($scope, $http) {
$http.get("customers.php").then(function(response) {
$scope.myData = response.data.records;
});
});
</script>
Application Explained:
The application defines the customersCtrlcontroller, with a $scopeand $http
object.
On success, the controller creates a property, myData, in the scope, with JSONdata from the
server.
Fetching Data From a PHP Server Running
MySQL
Angular JS Example
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []); app.controller('customersCtrl',
function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers_mysql.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
Fetching Data From an ASP.NET ServerRunning SQL
Angular JS Example
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []); app.controller('customersCtrl',
function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers_sql.aspx")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
Server Code Examples
The following section is a listing of the server code used to fetch SQL data.
Requests for data from a different server (than the requesting page), are called
cross-site HTTP requests.
Cross-site requests are common on the web. Many pages load CSS, images,and scripts from
different servers.
The following line, in our PHP examples, has been added to allow cross-siteaccess.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: *");
Server Code PHP and MySQL
<?php
header("Access-Control-Allow-Origin: *"); header("Content-Type:
application/json; charset=UTF-8");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {if
($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
$outp = "";
while (!$rs->EOF) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
$rs->MoveNext();
}
$outp ='{"records":['.$outp.']
$conn->close();
echo ($outp);
?>
Server Code ASP.NET, VB and MS Access
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Data"%>
< %@ Import Namespace="System.Data.OleDb"%>
<%
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json") Dim conn
As OleDbConnection
Dim objAdapter As OleDbDataAdapter
Dim objTable As DataTable
Dim objRow As DataRow
Dim objDataSet As New DataSet()
Dim outp
Dim c
conn = New OledbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data
source=Northwind.mdb")
objAdapter = New OledbDataAdapter("SELECT CompanyName, City, Country FROM
Customers", conn)
objAdapter.Fill(objDataSet, "myTable")
objTable=objDataSet.Tables("myTable")
outp = ""c
= chr(34)
for each x in objTable.Rows
if outp <> "" then outp = outp & ","
outp = outp & "{" & c & "Name" & c & ":" & c & x("CompanyName") & c & "," outp = outp
& c & "City" & c & ":" & c & x("City") & c & ","outp = outp & c & "Country" & c
& ":" & c & x("Country") & c & "}"next
outp ="{" & c & "records" & c & ":[" & outp & "]}"
response.write(outp)
conn.close
%>
Server Code ASP.NET, Razor C# and SQL Lite
@{
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json") var db =
Database.Open("Northwind");
var query = db.Query("SELECT CompanyName, City, Country FROM Customers");var
outp =""
var c = chr(34)
}
@foreach(var row in query)
{
if outp <> "" then outp = outp + ","
outp = outp + "{" + c + "Name" + c + ":" + c + @row.CompanyName + c + "," outp = outp +
c + "City" + c + ":" + c + @row.City + c + ","outp = outp + c + "Country" + c + ":" + c +
@row.Country + c + "}"
}
outp ="{" + c + "records" + c + ":[" + outp + "]}"@outp