One time binding with filter in AngularJS

Posted By : Ravi Verma | 25-Nov-2016

Binding With Filter in AngularJS

Create a html file with any name, say 'index.html'. copy the below code and paste into 'index.html' file. save it and open it on browser

In one-way binding, Object values are set to the isolate Component using the same value, the parent Object’s identity. When we break this identity, we’re technically “breaking” that identity binding and the parent’s $watch will not fire.

View is updated only once when it has anything other than undefined. so return undefined from filter if model does not have anything.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - One time binding with filter</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
  <script>
    (function(angular) {
  'use strict';
angular.module('oneTimeBidingExampleApp', []).
  controller('AppController', ['$scope', function($scope) {
    $scope.showNumber = function(clickEvent) {
      $scope.number = "123456789";
    };
  }])
  
  .filter('formatPhone', function ($rootScope) {
    return function filter( input ) {
      if (!input) return;

      if (input.length == 9) {
        input = "0"+input;
      };
      var str = input.toString();
      return str.slice(0, 3) + " " + str.slice(3, 6) + " " + str.slice(6, 8) + " " + str.slice(8, 10);
    }
  });
})(window.angular);
  </script>
</head>
<body ng-app="oneTimeBidingExampleApp">
  <div ng-controller="AppController">
  <button ng-click="showNumber($event)">Show Number</button>
  <p >One time binding: {{::(number|formatPhone)}}</p>
  <p >One time binding: <span ng-show="number">{{::number|formatPhone}}</span></p>
</div>
</body>
</html>

Hope you liked it, Thanks

 

About Author

Author Image
Ravi Verma

Ravi is a seasoned technologist with excellent experience in AngularJS , NodeJS and MEAN stack. He has good experience in developing complex UIs for web and mobile applications.

Request for Proposal

Name is required

Comment is required

Sending message..