Tuesday, May 26, 2015

Toturial angularjs with mvc 4

AngularJS Introduction



AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.



AngularJS is a JavaScript framework. It is a library written in JavaScript.

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



AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

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.



AngularJS Directives


The ng-init directive initialize AngularJS application variables.

Ex:

<div ng-app="" ng-init="Name='John'">

<p>The name is <span ng-bind="Name"></span></p>

</div>

AngularJS Expressions


AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS will "output" data exactly where the expression is written:
Ex.<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>
AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.
Ex.
<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p>{{name}}</p>
</div>

AngularJS Applications

AngularJS modules define AngularJS applications.
AngularJS controllers control AngularJS applications.
The ng-app directive defines the application, the ng-controller directive defines the controller.
Ex.
<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>

First way:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>

Second Way:
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>

AngularJS Module


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

angular.module : An Angular module is simply a collection of controllers, services, filters, directives, etc. that are initialized when the application is booted. Moreover its same like Main function of other langulages like C, C++ etc which is the entry point of the application.

AngularJS Controller

app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});

angular.Controller : Its contain business login behind the application same like MVC controller. Controllers are the entry-point into our front-end business logic, they contain all the methods and veriable that our view used. Controllers also allow us to initialize the scope, which will house both the data and the functions that we’ll want to run in the view.

$scope : Scope is nothing but an object that Glues the View with Controller. Scope uses Angular’s two-way data binding to bind model data to view. When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection.

AngularJS Numbers

Ex.
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
AngularJS Strings
<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is {{ firstName + " " + lastName }}</p>
<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>



AngularJS Objects


<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>

<p>The name is <span ng-bind="person.lastName"></span></p>
</div>AngularJS Arrays

<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
<p>The third result is <span ng-bind="points[2]"></span></p>
</div>



AngularJS Expressions vs. JavaScript Expressions


Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.

Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.

Unlike JavaScript expressions, AngularJS expressions do not support conditionals, loops, or exceptions.

Unlike JavaScript expressions, AngularJS expressions support filters.


AngularJS Filters

Filters can be added to expressions and directives using a pipe character.
AngularJS filters can be used to transform data:

Filter            Description
currency       Format a number to a currency format.
filter             Select a subset of items from an array.
lowercase     Format a string to lower case.
orderBy        Orders an array by an expression.

uppercase    Format a string to upper case.

<div ng-app="" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>

----------

<div ng-app="" ng-controller="personCtrl">
<p>The name is {{ lastName | lowercase }}</p>
</div>

------------

<div ng-app="" ng-controller="costCtrl">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
</div>

--------------

<div ng-app="" ng-controller="namesCtrl">
<ul>
  <li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
<div>

-------------------
<div ng-app="" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
  <li ng-repeat="x in names | filter:test | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>
</div>

AngularJS AJAX - $http

$http is an AngularJS service for reading data from remote servers.

AngularJS $http is a core service for reading data from web servers.
$http.get(url) is the function to use for reading server data.
<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.aspx")
    .success(function(response) {$scope.names = response.records;});
});
</script>


page :http://www.w3schools.com/angular/customers.aspx

{
"records": [
  {
    "Name" : "Alfreds Futterkiste",
    "City" : "Berlin",
    "Country" : "Germany"
  },
  {
    "Name" : "Berglunds snabbköp",
    "City" : "LuleÃ¥",
    "Country" : "Sweden"
  },
{
    "Name" : "Wolski Zajazd",
    "City" : "Warszawa",
    "Country" : "Poland"
  }
]
}

The AngularJS application is defined by ng-app. The application runs inside a <div>.
The ng-controller directive names the controller object.
The customersCtrl function is a standard JavaScript object constructor.
AngularJS will invoke customersCtrl with a $scope and $http object.
$scope is the application object (the owner of application variables and functions).
$http is an XMLHttpRequest object for requesting external data.
If success, the controller creates a property (names) in the scope, with JSON data from the server.

AngularJS Tables


Displaying with CSS Style

<style>
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;
}
</style>



Display the Table Index ($index)

<table>
  <tr ng-repeat="x in names">
    <td>{{ $index + 1 }}</td>
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

Using $even and $odd


<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>

           AngularJS SQL

Fetching data from sql server:    

@{

Response.AppendHeader("Access-Control-Allow-Origin", "*");

Response.AppendHeader("Content-type", "application/json");

var db = Database.Open("CPSMSConnectionStrings"); //Connection string from web.config

var query = db.Query("SELECT FirstName, Designation, Email FROM tbluser where userid=19");

var outp ="";
var c =':';
}
@foreach(var row in query)
{
if (outp != ""){
    outp = outp + ",";
}
outp = outp + "{" + c + "FirstName" + c + ":" + c + @row.FirstName + c + ",";
outp = outp + c + "Designation" + c + ":" + c + @row.Designation + c + ",";
outp = outp + c + "Email " + c + ":" + c + @row.Email + c + "}";
}
@outp

-----------

ng-disabled Directive

The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.

<div ng-app=""><p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
</div>

ng-show Directive

<div ng-app="">
<p ng-show="true">I am visible.</p>
<p ng-show="false">I am not visible.</p>
</div>

Hiding HTML Elements

The ng-hide directive can be used to set the visibility of a part of an application.
The value ng-hide="true" makes an HTML element invisible.
The value ng-hide="false" makes the element visible.
<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John",
    $scope.lastName = "Doe"
    $scope.myVar = false;
    $scope.toggle = function() {
        $scope.myVar = !$scope.myVar;
    };
});
</script>


AngularJS Input Validation

AngularJS forms and controls can validate input data.

Ex.
<form  ng-app="myApp"  ng-controller="validateCtrl"
name=
"myForm" novalidate>

<p>Username:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Username is required.</span>
  </span>
</p>

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Email is required.</span>
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>
  </span>
</p>

<p>
  <input type="submit"
  ng-disabled=
"myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid"
>
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
    $scope.user = 'John Doe';
    $scope.email = 'john.doe@gmail.com';
});
</script>


AngularJS API


AngularJS Global API


The AngularJS Global API is a set of global JavaScript functions for performing common tasks like:

  • Comparing objects
  • Iterating objects
  • Converting data
The Global API functions are accessed using the angular object.
API                          Description
angular.lowercase() Converts a string to lowercase
angular.uppercase() Converts a string to uppercase
angular.isString() Returns true if the reference is a string
angular.isNumber() Returns true if the reference is a number

Ex.
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ x1 }}</p>
<p>{{ x2 }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.isNumber($scope.x1);

//$scope.x2 = angular.lowercase($scope.x1);
//$scope.x2 = angular.uppercase($scope.x1);//$scope.x2 = angular.isString($scope.x1);
});
</script>



AngularJS and Twitter Bootstrap

Bootstrap is a popular style sheet. This chapter demonstrates how to use it with AngularJS.
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

Ex.

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp" ng-controller="userCtrl">

<div class="container">

<h3>Users</h3>

<table class="table table-striped">
  <thead><tr>
    <th>Edit</th>
    <th>First Name</th>
    <th>Last Name</th>
  </tr></thead>
  <tbody><tr ng-repeat="user in users">
    <td>
      <button class="btn" ng-click="editUser(user.id)">
      <span class="glyphicon glyphicon-pencil"></span>&nbsp;&nbsp;Edit
      </button>
    </td>
    <td>{{ user.fName }}</td>
    <td>{{ user.lName }}</td>
  </tr></tbody>
</table>

<hr>
<button class="btn btn-success" ng-click="editUser('new')">
  <span class="glyphicon glyphicon-user"></span> Create New User
</button>
<hr>

<h3 ng-show="edit">Create New User:</h3>
<h3 ng-hide="edit">Edit User:</h3>

<form class="form-horizontal">
<div class="form-group">
  <label class="col-sm-2 control-label">First Name:</label>
  <div class="col-sm-10">
    <input type="text" ng-model="fName" ng-disabled="!edit" placeholder="First Name">
  </div>
</div> 
<div class="form-group">
  <label class="col-sm-2 control-label">Last Name:</label>
  <div class="col-sm-10">
    <input type="text" ng-model="lName" ng-disabled="!edit" placeholder="Last Name">
  </div>
</div>
<div class="form-group">
  <label class="col-sm-2 control-label">Password:</label>
  <div class="col-sm-10">
    <input type="password" ng-model="passw1" placeholder="Password">
  </div>
</div>
<div class="form-group">
  <label class="col-sm-2 control-label">Repeat:</label>
  <div class="col-sm-10">
    <input type="password" ng-model="passw2" placeholder="Repeat Password">
  </div>
</div>
</form>

<hr>
<button class="btn btn-success" ng-disabled="error || incomplete">
  <span class="glyphicon glyphicon-save"></span> Save Changes
</button>
</div>

<script>
angular.module('myApp', []).controller('userCtrl'function($scope) {
$scope.fName = '';
$scope.lName = '';
$scope.passw1 = '';
$scope.passw2 = '';
$scope.users = [
{id:1, fName:'Hege',  lName:"Pege" },
{id:2, fName:'Kim',   lName:"Pim" },
{id:3, fName:'Sal',   lName:"Smith" },
{id:4, fName:'Jack',  lName:"Jones" },
{id:5, fName:'John',  lName:"Doe" },
{id:6, fName:'Peter', lName:"Pan" }
];
$scope.edit = true;
$scope.error = false;
$scope.incomplete = false

$scope.editUser = function(id) {
  if (id == 'new') {
    $scope.edit = true;
    $scope.incomplete = true;
    $scope.fName = '';
    $scope.lName = '';
    } else {
    $scope.edit = false;
    $scope.fName = $scope.users[id-1].fName;
    $scope.lName = $scope.users[id-1].lName; 
  }
};

$scope.$watch('passw1',function() {$scope.test();});
$scope.$watch('passw2',function() {$scope.test();});
$scope.$watch('fName'function() {$scope.test();});
$scope.$watch('lName'function() {$scope.test();});

$scope.test = function() {
  if ($scope.passw1 !== $scope.passw2) {
    $scope.error = true;
    } else {
    $scope.error = false;
  }
  $scope.incomplete = false;
  if ($scope.edit && (!$scope.fName.length ||
  !$scope.lName.length ||
  !$scope.passw1.length || !$scope.passw2.length)) {
       $scope.incomplete = true;
  }
};

});


</script>
</body>
</html>
AngularJS Includes
With AngularJS, you can include HTML files in HTML.

HTML Includes in Future HTML

Including a portion of HTML in HTML is, unfortunately, not (yet) supported by HTML.
<link rel="import" href="/path/navigation.html">

<!DOCTYPE html>
<html ng-app="">
<link rel="stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-controller="userCtrl">

<div class="container">
<div ng-include="'myUsers_List.htm'"></div>
<div ng-include="'myUsers_Form.htm'"></div>
</div>

<script src= "myUsers.js"></script>

</body>
</html>