AngularJs Interpolate Filter

This might be a simple angular filter, but more helpful to reduce ugly code in your controller.

Angular provides '$interpolate' service to evaluate angular expressions. 

Consider you have some constant template with some expression expecting a dynamic value - lets say userName.

Example:
//example.js
angular.module('app.example',[])
.constant('TEMPLATE',{
   WELCOME_MSG: 'Hi {{userName}} Welcome to our Portal'
})
.controller('sampleCtrl', function($scope, TEMPLATE, $interpolate){
   
   $scope.data = {
      userName:'Ajai'
   };

   $scope.MSG = $interpolate(TEMPLATE.WELCOME_MSG)($scope.data);
   
});


<!--example.html-->
<div ng-app="app.example" ng-controller="sampleCtrl">
<h1>{{MSG}}</h1>
</div>

Instead you can simplify the above one with custom interpolate filter. Below example wont make much difference, but consider if you have some 100 template constants - it is not a good idea to evaluate each template expression in controller. Instead we can achieve the same in template expression with simple filter.

angular.module('angular.filter.interpolate')
        .filter('interpolate', function ($interpolate) {
            return function (input, data) {
                return input?$interpolate(input)(data):'';
            };
        });

Example:
//example.js
angular.module('app.example',['angular.filter.interpolate'])
.constant('TEMPLATE',{
   WELCOME_MSG: 'Hi {{userName}} Welcome to our Portal'
})
.controller('sampleCtrl', function($scope, TEMPLATE, $interpolate){
   
   $scope.TEMPLATE = TEMPLATE;

   $scope.data = {
      userName:'Ajai'
   };
   
});
<!--example.html-->
<div ng-app="app.example" ng-controller="sampleCtrl">
    <!--Referring the model-->
    <h1>
      {{TEMPLATE.WELCOME_MSG | interpolate:data}}
    </h1>
    <!--With hardcoded value-->
    <h1>
      {{TEMPLATE.WELCOME_MSG | interpolate:{userName:'Ajai'} }}
    </h1>
</div>


Popular posts from this blog

Simple Animation Using C

Personal Diary - A Mini Project Written in Turbo C With Graphical Interface

2D Reflection