2

I have a api returned json which i am binding to a form elements via ng model

the returned data from api is in UPPERCASE, how can i apply filter / css? to get each first letter in all words to be capital

<input type = text ng-model = string>

need to make this string binded by the value(obtained via API) in controller to be in camel case

SAN
  • 326
  • 6
  • 23

3 Answers3

1

Use angular's lowercase filter and then transform text with css.

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.string = 'LOREM IPSUM DOLOR SIT AMET, DUIS VIDIT DEFINITIONES MEL NE'
});
input {
  text-transform: capitalize;
  padding:10px;
}
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app=myApp ng-controller=myCtrl>
  <input type=text ng-model="string | lowercase" >
</div>
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
  • One issue im facing with this approach [link]https://docs.angularjs.org/error/ngModel/nonassign?p0=profile.st%20%7C%20lowercase&p1=%3Cinput%20type%3D%22text%22%20class%3D any idea how to resolve? – SAN Apr 28 '17 at 11:22
  • I don't have much idea about this error, filter is still working even with error that's the strange thing, may be you can ask another question with this error. – Abhishek Pandey Apr 28 '17 at 11:36
  • 1
    resolved the issue by replacing ng-model with value={{string | lowercase}} – SAN May 04 '17 at 11:10
0

You can use this solution.

 var app = angular.module('app', []);
 app.controller('Ctrl', function ($scope) {
   $scope.msg = 'hello, world.';
  });

app.filter('capitalize', function() {
   return function(input) {
     return (!!input) ? input.charAt(0).toUpperCase() + 
     input.substr(1).toLowerCase() : '';
  }
});

view must be like this

<p><b>My Text:</b> {{msg | capitalize}}</p>
Wintergreen
  • 236
  • 1
  • 9
0

You can use a vanilla JavaScript solution:

function capitalize(str){
    if(!str || typeof str !== 'string')
        return ""

    var newString = str; 
    var firstLetter = str[0];
    newString = newString.toLowerCase().slice(1, newString.length);

    return [firstLetter, newString].join('');
}

Otherwise you can use an AngularJS filter

angular
    .module('app')
    .filter('capitalize', capitalize)

Where capitalize is the very same function I have written above. This gives you ability to use this directly in the view:

<span>{{::vm.value | capitalize}}</span>
Phugo
  • 400
  • 1
  • 10