Friday 15 January 2016

Angularjs Tutorial for beginners – Part2

Continuing the article what I left in previous article; will cover.

·         What is AngularJS  Filters
·         How to use AngularJS Events             
·         How to do Validation in AngularJS Forms
·         How to use $http in Angular JS
·         How to call service or WebAPI in AngularJS 

Please see the part one before proceeding with this article.


1.    AngularJS Filters



Using Filers we can format the value to display the user.
Using filters in view templates.
       Filters can be applied to expressions e.g. {{ expression | filter }}
       Built in Filter for angularJS as
Number
Format Number toText
currency
Format a number to  currency.
filter
Get 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.

Lab  5:
If  you will see the below code snippet we defined the ng-app, ng-controller. As I already describe in first article now there we are using the Currency filter in example and type of currency that will reflect on view.

Using of Upper case and Lower case filter. Which will convert your text to upper and lower respectively.

And number filter.

Code snippet :
<h2>Sample5 - Using filters in view templates</h2>

<div ng-app="myApp" ng-controller="Viewfilters">

    @*Currency Filter*@
    <br /><br /><br />
    <u><b>Currency Filter </b></u>
    <br /><br />
    Money: <input type="text" ng-model="Money"><br>
    Default Amount : {{ Money | currency}} <br />
    Custom Amount : {{ Money | currency: "₹"}}

    @*Lower case and upper case filter*@
    <br /><br /><br />
    <u><b>Lower/Upper Case Filter </b></u>
    <br /><br />
    Name: <input type="text" ng-model="Name"><br>
    Name(UpperCase) : {{ Name | uppercase}} <br />
    Name(lowercase) : {{ Name | lowercase}} <br />


    <br /><br /><br />
    <u><b>Number Filter </b></u>
    <br /><br />
    Number of Employee: <input type="text" ng-model="AverageSalary"><br>
    Average Salary : {{ AverageSalary | number}} <br />
    Average Salary(2 digit) : {{ AverageSalary | number:2}} <br />
</div>

<script>

    angular.module('myApp', []).controller('Viewfilters', ['$scope', function ($scope) {
        $scope.Money = 1234.56;
        $scope.Name = "Satya Rathore";
        $scope.AverageSalary = 1234.5612;
    }]);
</script>

Screen Output



Lab  6:

Using filters in controllers, services, and directives

Avoid Loading of huge data
If you will see the code we are getting the data from data base as all records and now we want only few of the records will display on the browser so there we are going to provide the filter so it will filter the records and display into the browser.

Code snippet :

Here filtering the records which is matching with ‘a’
Or there we can give the inline filter
<h2>Sample6</h2>

<div ng-app="MyApp" ng-controller="FilterController"> @*Defining the alies  to use it*@

    <b><u>Searching(Filtering) the binded Data</u></b><br /><br />
    <div>
        Search Name : <input type="text" ng-model="search"> <br />
        <b> All entries:</b>
        <span ng-repeat="entry in AllRecords | filter:search | orderBy:'name'"><br />{{entry.name}}  </span@*Inline filter *@
    </div>
    <br /><br />
    <b><u>Bind Data After Filteration</u></b><br /><br />
    <div>
        <b> Entries that contain an "a":</b>
        <span ng-repeat="entry in filteredRecords"><br />{{entry.name}} </span>
    </div>
</div>

<script>

    angular.module('MyApp', []).
controller('FilterController', function ($scope,$filter) {
    $scope.AllRecords = [
      { name: 'Tobias' },
      { name: 'Jeff' },
      { name: 'Brian' },
      { name: 'Igor' },
      { name: 'James' },
      { name: 'Brad' }
    ];
    $scope.filteredRecords = $filter('filter')($scope.AllRecords, { name: "a" });
});
</script>

Screen Output




*Note: you can create your own custom filter also.

2.    AngularJS Events


       creating more advanced AngularJS applications your application will
 need to handle DOM events like mouse clicks, moves, keyboard presses, change events
       Events in Angular JS as
§  ng-click
§  ng-dbl-click
§  ng-mousedown
§  ng-mouseup
§  ng-mouseenter
§  ng-mouseleave
§  ng-mousemove
§  ng-mouseover
§  ng-keydown
§  ng-keyup
§  ng-keypress
§  ng-change

Lab  7:

Code snippet :
For click event in angular we are using ng-click and while clicking the event we are increasing the count and showing the alert message with count.
It showing the example of two way data binding also.

<h2>Sample7 - Click Event in AngularJS</h2>

<div ng-app="myApp" ng-controller="myCtrl">

    <button ng-click="count = count + 1">Click me!</button> <br />

    <p>{{ count }}</p>

    <br /><br />
    <button ng-click="getalert()">Get Alert</button>
</div>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope) {
        $scope.count = 0;

        $scope.getalert = function()
        {
            window.alert("get count" + $scope.count);
        }
    });
</script>

Output Screen

 

AngularJS Forms


       Form is a collection of controls for the purpose of grouping related controls together.
       Form and controls provide validation services, so that the user can be notified of invalid input before submitting a form
        two-way data-binding by synchronizing the model to the view, as well as view to the model.

Lab  8:

Code snippet :
Placed and make the container for your model and it will be in one form. This form we can use for validation purpose also.
There we have master records and on resetting we are resetting the value of inserted value of form.

<h2>Sample8 - Angular Forms</h2>

<div ng-app="myapp" ng-controller="ExampleController">
    <form novalidate class="simple-form">
        Name: <input type="text" ng-model="user.name" /><br />
        E-mail: <input type="email" ng-model="user.email" /><br />
        Gender: <input type="radio" ng-model="user.gender" value="male" />male
        <input type="radio" ng-model="user.gender" value="female" />female<br />
        <input type="button" ng-click="reset()" value="Reset" />
        <input type="submit" ng-click="update(user)" value="Save" />
    </form>
    <pre>user = {{user | json}}</pre>
    <pre>master = {{master | json}}</pre>
</div>

<script>
    angular.module('myapp', [])
      .controller('ExampleController', ['$scope', function ($scope) {
          $scope.master = { name: "John", email: "Doe" , gender:"male"};


          $scope.reset = function () {
              $scope.user = angular.copy($scope.master);
          };

          $scope.reset();
      }]);
</script>

Output will be the normal form screen


AngularJS  Input Validation


AngularJS forms and controls can provide validation services, and notify users of invalid input.
Please see the code snippet based on the operation it will show the message and it will aloow that pattern only for validation ng-show="form.$submitted || form.inpName.$touched"> it email check that form submitted on touched and show the error.
ng-show="form.inpEmail.$error.required" it shows as the field is required and if you not feed any data.

ng-pattern="gender.word" will check the pattern for the input values
For gender it defined as M/F like     $scope.gender = {
        text: 'M',
        word: "^(M|F|M/F)$"
    };

Lab  9:

Code snippet :

<div ng-app="myApp" ng-controller="ValidationController">
    <form name="form" class="css-form" novalidate>
        Name:
        <input type="text" ng-model="user.name" name="inpName" required="" />
        <br />
        <div ng-show="form.$submitted || form.inpName.$touched">
            <div ng-show="form.inpName.$error.required" style="color:red">Name Required.</div>
        </div>

        E-mail:
        <input type="email" ng-model="user.email" name="inpEmail" required="" />
        <br />
        <div ng-show="form.$submitted || form.inpEmail.$touched">
            <span ng-show="form.inpEmail.$error.required" style="color:red">Email required.</span>
            <span ng-show="form.inpEmail.$error.email" style="color:red">Please enter valid email.</span>
        </div>

        @* Regular expression validation*@
        Gender :
        <input type="text" ng-model="user.gender" ng-pattern="gender.word" ng-trim="false" name="inpGender" required="" />
        <br />
        <div ng-show="form.$submitted || form.inpGender.$touched">
            <span ng-show="form.inpGender.$error.required" style="color:red">Gender required.</span>
            <span ng-show="form.inpGender.$error.pattern" style="color:red">Enter one digist M/F.</span>
        </div>


        <input type="submit" ng-click="update(user)" value="Save" />
        <pre>user = {{user | json}}</pre>
    </form>
 
</div>
<script>
    angular.module('myApp', [])
.controller('ValidationController', ['$scope', function ($scope) {
    $scope.master = {};
  
    $scope.gender = {
        text: 'M',
        word: "^(M|F|M/F)$"
    };

    $scope.update = function (user) {
       $scope.master = angular.copy(user);
        if ($scope.form.$valid) {
            window.alert("Record save successfully");
        }
    };
}]);
</script>

Output screen


AngularJS $http and SQL Integration


       $http.Get use to  ajax call for controller in Angular
       By using the $http.get we can call the web Api also


Lab  9:

Code snippet
We need to use $http to get the records from service or DB.  We need to inject $http to function
<div ng-app="MyApp" ng-controller="DataFetch">
    <table>
        <tr>
            <td> Name :: {{contacts.Name}}</td>
        </tr>
        <tr>
            <td> Address :: {{contacts.Address}}</td>
        </tr>
    </table>

</div>

<script>
    var app = angular.module('MyApp', [])

    app.controller('DataFetch', function ($scope, $http) {
        $scope.contacts = null;
        $http.get('/Data/GetLastContact').then(function (d) {
            $scope.contacts = d.data;
        }, function () {
            alert("failed");
        });
    })
</script>
GetLastContact
public class DataController : Controller
    {
        //
        // GET: /Data/
        public JsonResult GetLastContact()
        {
            UserDetail ud = null;
            using (FetchRecordsEntities ur = new FetchRecordsEntities())
            {
                ud = ur.UserDetails.OrderByDescending(o => o.Id).FirstOrDefault();

            }
            return new JsonResult { Data = ud, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
       }

Output Screen


Practice application Login Form in AngularJS
http://www.getmscode.com/2015/11/angularjs-with-mvc-login-form-tutorial.html
Sample crud operation
http://www.getmscode.com/2016/03/simple-crud-operation-using-angularjs.html

No comments:

Post a Comment