Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

AngularJS Form

Form is group of related html controls together, you can use from to wire required controls and reuse it.

You can use html controls like,

1. Input Fields

2. Select Fields

3. Buttons

i.e Text-area, textbox, radio-button, checkbox, button etc.

Data binding with Forms

AngularJS provides some features for binding data of HTML form input fields to the model object ($scope). These features makes it easier to work with forms.

The ng-model directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model.

In following example we used two way data binding for form textbox controls,

<div ng-controller="MyEmoloyeeCntrlr">

  <form>

   First name :<input type="text" name="firstName" ng-model="Employee.FirstName"> <br />

   Last name: <input type="text" name="lastName" ng-model="Employee.LastName"> <br />

  </form>

 

   <div>

      {{Employee.FirstName |uppercase }} {{Employee.LastName | uppercase}}

   </div>

  </div>

 

    <script>

        angular.module("myFormApp", [])

                .controller("MyEmoloyeeCntrlr", function ($scope) {

                    $scope.Employee = {};

                    $scope.Employee.FirstName = "Nagnath";

                    $scope.Employee.LastName = "Kendre";

                });

    </script>

 

Form control events and validation

AngularJS provides some event directives which can be associated with the HTML controls.

Following are some AngularJS supported events,

ng-mousedown
ng-mouseover
ng-click
ng-dbl-click
ng-mouseenter
ng-keydown
ng-keyup
ng-change etc.

Following example with ng-click reset form data,

Example

   <div ng-controller="MyEmoloyeeCntrlr">
     <form>
      Full name :<input type="text" name="firstName" ng-model="Employee.FullName"> <br />
            <button ng-click="Employee.FullName = ''">
                Reset
            </button>
      </form>
   
    </div>
    <script>
        angular.module("myFormApp", [])
                .controller("MyEmoloyeeCntrlr", function ($scope) {
                    $scope.Employee = {};
                    $scope.Employee.FullName = "Nagnath Kendre";
                });
    </script>

 

Validation

You can use following CSS to display validity of each form control.

ng-valid: the model is valid
ng-invalid: the model is invalid
ng-valid-[key]: for each valid key added by $setValidity
ng-invalid-[key]: for each invalid key added by $setValidity
ng-pristine: the control hasn't been interacted with yet
ng-dirty: the control has been interacted with
ng-touched: the control has been blurred
ng-untouched: the control hasn't been blurred
ng-pending: any $asyncValidators are unfulfilled

Note: “novalidate” is used to disable browser's native form validation.

Validation Example

    <!--Angular view Code-->
    <div ng-controller="EmployeeController">
        <form novalidate class="css-form">
            User Name :<input type="text" name="UserName" ng-model="Employee.UserName" required> <br />
            Full Name :<input type="text" name="Name" ng-model="Employee.Name"> <br />
            Email :<input type="email" ng-model="Employee.Email"> <br />
          
            <button ng-click="reset()"> Reset</button>
            <input type="submit" ng-click="update(Employee)" value="Save" />
 
            <pre>user = {{Employee | json}}</pre>
            <pre>Updated Data = {{UpdatedData | json}}</pre>
        </form>
 
    </div>
 
    <!--css validation-->
    <style type="text/css">
        .css-form input.ng-invalid.ng-touched {
            background-color: #0094ff;
        }
 
        .css-form input.ng-valid.ng-touched {
            background-color: #ff6a00;
        }
    </style>
 
    <!--Angular script Code-->
    <script>
       angular.module('myApp', []).controller('EmployeeController', ['$scope', function ($scope) {
           $scope.UpdatedData = {};
 
           $scope.update = function (Employee) {
               $scope.UpdatedData = angular.copy(Employee);
           };
 
           $scope.reset = function () {
               $scope.Employee = angular.copy($scope.UpdatedData);
           };
 
           $scope.reset();
        }]);
    </script>

 

Binding data to form control and control state

Form is an instance of form controller, you can publish form instance into scope using name attribute.

The input control that has ng-moel directive that holds instance of ngModelController, In this scenario a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.

With above explanation we can conclude that the internal state of both the form and the control is available for binding in the view using the standard binding primitives.

Example:

<body ng-app="myApp" >
 
    <!--Angular view Code with form name and control name attribute-->
    <div ng-controller="EmployeeController">
        <form name="EmployeeForm" class="css-form" novalidate>
            User Name :<input type="text" name="uName" ng-model="Employee.UserName" required> <br />
 
            <div ng-show="EmployeeForm.$submitted || EmployeeForm.uName.$touched">
                <div ng-show="EmployeeForm.uName.$error.required">User Name is required field.</div>
            </div>
            Full Name :<input type="text" name="fName" ng-model="Employee.Name"> <br />
            Email :<input type="email" ng-model="Employee.Email" name="uEmail" required> <br />
 
            <div ng-show="EmployeeForm.$submitted || EmployeeForm.uEmail.$touched">
                <span ng-show="EmployeeForm.uEmail.$error.required">Tell us your email.</span>
                <span ng-show="EmployeeForm.uEmail.$error.email">This is not a valid email.</span>
            </div>
 
            <button ng-click="reset()"> Reset</button>
            <input type="submit" ng-click="update(Employee)" value="Save" />
 
            <pre>user = {{Employee | json}}</pre>
            <pre>Updated Data = {{UpdatedData | json}}</pre>
        </form>
 
    </div>
 
    <!--Angular script Code used state in data binding and validation-->
    <script>
       angular.module('myApp', []).controller('EmployeeController', ['$scope', function ($scope) {
         
           $scope.UpdatedData = {};
           $scope.update = function (Employee) {
               $scope.UpdatedData = angular.copy(Employee);
           };
 
           $scope.reset = function (EmployeeForm) {
               if (EmployeeForm) {
                   EmployeeForm.$setPristine();
                   EmployeeForm.$setUntouched();
               }
               $scope.Employee = angular.copy($scope.UpdatedData);
           };
 
           $scope.reset();
        }]);
    </script>
 
</body>

 धन्यवाद मित्रानो ... 

AngularJS Service

In daily life term Service!!

Simple explanation of term “service” is doing work for someone, example in hotel Chef provides service to hotel or he is doing work for customers.

In technical language

A service offered by a one resource or device to another resource or device communicating with each other via the World Wide Web.

What is AngularJS Service?

In simple word AngularJS service is an object that does some sort of work.

With AngularJS service objects are wired together using dependency injection (DI), you can use service to organize, share and reuse code.

Why AngularJS service?

Following are four main reasons JavaScript applications require Service

1. Code organizing and architecture

2. Code share and code reuse

3. Loosely coupled binding

4. Solid principles like Single Responsibility Principle (SRP) and the Dependency Inversion Principle (DIP).


Inbuilt AngularJS Services

AngularJS provides some inbuilt Services following are some,

$http, $route, $window, $location, $animate, $compile, $filter, $locale etc.

Using inbuilt Service Example

With Following code example we used inbuilt service $http to retrieve data from server

  <script>
    var myApp = angular.module("myApp",[]);
    myApp.controller('myCtrl',function($scope, $http) {
 
    var url = "https://test.codechef4u.com/usersData/users?userid=nk54ts";
    $http.get(url).then(function(response) {
     $scope.users = response.data;
   });
   });
 </script>

 

Angular services are,

Lazily instantiated
Angular only instantiates a service when an application component depends on it.
Factory or Singletons
Each component dependent on a service gets a reference to the single instance generated by the service factory.


Creating a custom service

You can create your own service using following two approach,

Factory

Using factory method you first define factory and then assign method to it, check following sample example for clear understanding.

Example

    <script>
    var CalcApp = angular.module("mathApp", []);
    CalcApp.factory('CalService', function () {
    var factory = {};
 
    factory.AddNumbers = function(a, b, c ) {
    return a + b + C
    }
 
    return factory;
    });
    </script>

Service

With service first define service and then assign method to it, check following sample example for clear understanding.

Example

   <script>
    var CalcApp = angular.module("myApp", []);
    CalcApp.service('CalcService', function () {
        this.myFunc = function (a,b) {
            return a-b;
        }
    });
    </script>

धन्यवाद मित्रानो ... 


AngularJS limitTo Filter

    What is AngularJS limitTo Filter?

     AngularJS limitTo Filter,

      1.     Allows you to create new array or string containing only a specified number of elements.

      2.     The array elements are considered either from beginning or end of source (array, string, numbers), specified by the value and sign (positive or negative) of limit.

      3.      If you are using input filed then its value is converted into string.

      Syntax:

{{object | limitTo : limit : begin }}

Parameter value

Description

limit

A number count specify number of elements to return.

begin

This is optional parameter, a number specify where to begin limitation.

 

Example:

<body>
    <div ng-app="myApp" ng-controller="EmployeeController">
        Id: {{Employee.id}}
        <br />
        User Name:{{Employee.userName }}
 
        <!--limitTo filter -->
        <ul>
            <li data-ng-repeat="myObject in Employee.Projects | limitTo : -2">id:{{myObject.id}} name:{{myObject.name}} Team Size:{{myObject.TeamSize}}</li>
        </ul>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('EmployeeController', ['$scope', function ($scope) {
            $scope.Employee = {
                id: 1,
                userName: 'sKendre;',
                name: 'Shourya Kendre',
 
                Projects: [
                    { id: 1, name: 'E shop', TeamSize: 5, isActive: true },
                    { id: 2, name: 'Employee Notifier', TeamSize: 3, isActive: true },
                    { id: 3, name: 'CRM', TeamSize: 10, isActive: false }
                ]
            };
        }]);
    </script>
</body>