codeMayfair codeMayfair - 1 month ago 6
AngularJS Question

Substr in angularJS to fetch the initials of the full name

My question is related to creating substr in Angular.JS

Suppose i have a model:

$scope.myName = 'John Smith'


but when during the rendering of the model on the page i need only the initials of the name like:

<p>{{myName | some directive/filter }}<p>


Output should be :: JS

i tried creating many directives but unable to fetch the exact output even i have tried the limitTo filter but it give only the starting first 2 letters of the name.

Workbook is here

Answer
angular
    .module('myApp',[])
    .run(function($rootScope){
        $rootScope.title = 'myTest Page';
    })
    .controller('testController', ['$scope', function($scope){


        $scope.myName = 'saurabh raman';
    }]).filter('filter', function() {

return function(input) {

    var name = input;
    var inls = name.match(/\b\w/g) || [];
    inls = ((inls.shift() || '') + (inls.pop() || '')).toUpperCase();
    return inls;
  }
});

view

<p>{{myName | filter}}</p>
  </body>

</html>
Comments