One time binding with filter in AngularJS
Posted By : Ravi Verma | 25-Nov-2016
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.