Showing posts with label 2-way binding. Show all posts
Showing posts with label 2-way binding. Show all posts

Sunday, August 9, 2015

AngularJS Basics

AngularJS is a Javascript framework which makes it incredibly easy to build web applications

Features of AngularJS: There are many features in AngularJS, primarily 2-way data binding, OO way of JS development, easy mapping between dom and JS model, Create custom tags, Dirty check on objects, implementing Routers.

Components:
  • RouteProvider
  • AngularJS templates (or) partials. 
  • Module
  • Controller

MVC: 
  • View holds the html fragments
  • Controller - holds the action to be performed
  • Model: holds data by getting from the REST services. 

Some attributes: 
  • ng-app: tell that this html page contains angularJS app
  • ng-model: bind the model to the div
  • ng-bind: used to bind the input tag to the model
  • ng-repeat: used to iterate through a list of model and display content. 
  • ng-controller: defines the controller that will be used for this div or section. 
  • ng-show | ng-hide: hide or show a div or section
  • ng-include: include another file in the html


AngularJS Directives: 
You can use directives in different ways:
  • As an attribute to a tag. 
  • As an element
  • As a class
  • As a comment
ng-init: used to initialise angularJS variables

You can also create custom directives: 

You have to use .directive method in the module to define a directive
myAppModule.directive('colorList', function () {
    return {
        restrict: 'AE',
        template:
              "<button ng-click='showHideColors()' type='button'>"
            + "{{isHidden ? 'Show Available Colors' : 'Hide Available Colors'}}"
            + "</button><div ng-hide='isHidden' id='colorContainer'>"
            + "</div>"

        }
});

AngularJS validation: 
  • $dirty
  • $valid
  • $invalid
  • $pristine

AngularJS Expressions: 
<p>My first expression: {{ 5 + 5 }}</p>
(or) 
<p>My first expression: {{ emp.getValue }}</p>
where emp is a angularJS model. 

AngularJS Filters: used to filter a list of values and display 
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>

You can also create custom filters in AngularJS:


Events:
  • ng-click
  • ng-double-click

Angular Services:
$http: 
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function(response) {$scope.names = response.records;});
});

var promise = $http({method: 'POST', url: 'memberservices/register', data: theData});

$window: represents browser window object. 
$location: gets information about the url and gives it to your application
$document: jqlite reference

You can also create custom services: 



—————————— Code Snippets ————————
Simplest AngularJS program
Enter your name : <input type="text" ng-model="ename">
Hello {{ ename }}
<script type="text/javascript" src="../js/lib/angular.min.js"></script>

Sample app code: 
<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>

RouteProvider: used to define which AngularJS controller to call when you hit a URL
helloWorldApp.config(['$routeProvider', '$locationProvider', 
function($routeProvider, $locationProvider){ 
 $routeProvider
   when('/', { 
     templateUrl: 'partials/main.html', 
     controller: 'MainCtrl' }).
   when('/show', { 
     templateUrl: 'partials/show.html', 
     controller: 'ShowCtrl' 
}); 

AngularJS Templates: 
  • ng-view

AngularJS Controllers: 
  • Define methods which would inturn get the data from the server
      • use $http
var addonsControllers = 
  angular.module('addonsControllers', []);

addonsControllers.controller('AddonsCtrl', 
  ['$scope', 'checkCreds', '$location', 'AddonsList', '$http', 'getToken',
    function AddonsCtrl($scope, checkCreds, $location, AddonsList, 
      $http, getToken) {
        if (checkCreds() !== true) {
            $location.path('/loginForm');
        }

        $http.defaults.headers.common['Authorization'] = 
          'Basic ' + getToken();
        AddonsList.getList({},
           function success(response) { 
              console.log("Success:" + 
                     JSON.stringify(response));
                    $scope.addonsList = response;
           },
           function error(errorResponse) {
              console.log("Error:" + 
                     JSON.stringify(errorResponse));                   
           }
        );
        $scope.addonsActiveClass = "active";
}]);

ng-repeat
<li ng-repeat="phone in phones | filter:query">
          {{phone.name}}
          <p>{{phone.snippet}}</p>
        </li>


External controllers: 
<div ng-app="myApp" ng-controller="personCtrl">

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 src="personController.js"></script>

Thursday, June 19, 2014

2-way Data binding


A model is a javascript object (data holder) which holds information for the view to render and controller to process. To define a model, just assign them to $scope scope. 

Example:
$scope.ename="Deiveehan Nallazhagappan";

The values can be single value, any valid javascript object or even an array. 

<body>

A controller is a AngularJS javascript object which is tied to the view. Its main responsibility is to provide default values to the model and supplement them with more UI specific functionalities. 

<div ng-controller="Student">
Enter your name : <input type="text" ng-model="ename">
<br>

Hello {{ ename }}
</div>


<script type="text/javascript" src="../js/lib/angular.min.js"></script>
<script type="text/javascript">
var Student = function($scope) {
       $scope.ename="Deiveehan Nallazhagappan";
}

</script>

Note:
--       ng-controller is an attribute used to map a controller to a view.
-          The controller object is available only to that view.
-          $scope object in the controller is a special object which contains custom models. In this case, the ename attribute is available in the scope object which is available only to that div having the controller.

In the above code, the ename attribute is modified when the page loads. This is done using the sentence

$scope.ename="Deiveehan Nallazhagappan";

And the data is updated both in the label and the text box. And whenever you modify the data in the textbox, the data is updated in the model.
This is called 2-way data binding and is a very important feature of AngularJS.