Making a custom directive with a function

时间:2017-06-19 14:06:10

标签: javascript angularjs

While working I come up with this problem, I made a dashboard on which user's image is loaded & if no image is provided by the user then a fallback image with his name initials is shown.

 <img class="md-avatar"  ng-src="{{item.image}}" ng-show="item.image"/>
 <div ng-hide="item.image" class="avatar" ng-if="!item.image">{{vm.initials(item.name)}}</div>

 vm.initials: function(fullName) {
            var initials = [];
            var k;
            initials.push(fullName[0]);
            for(var i=1 ; i<fullName.length ; i++){
                if(fullName[i]==' '){
                    initials.push(fullName[i+1].toUpperCase());
                }
            }
            if(initials.length == 1){
                initials.push(fullName[1]);
            }
            k  =  initials[0].toUpperCase();
            k+=initials[1];
            return k;

    }

This is working fine but the problem is I want to use this at multiple places so I have to add vm.initials function at every place. I've tried to make a directory in angular but failed, can anyone help in making a directory or any new approach.

0 个答案:

没有答案