Wielka litera pierwszej litery łańcucha w AngularJs

Chcę kapitalizować pierwszy znak łańcucha w angularjs

Jak użyłem {{ uppercase_expression | uppercase}} to konwertuje cały łańcuch na wielkie litery.

Author: Alex Man, 2015-05-13

20 answers

Użyj filtra kapitalizującego

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() : '';
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <p><b>My Text:</b> {{msg | capitalize}}</p>
    </div>
</div>
 214
Author: Nidhish Krishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-01 05:49:08

Powiedziałbym, że nie używaj angular / js, ponieważ możesz po prostu użyć css zamiast tego:

W css Dodaj klasę:

.capitalize {
   text-transform: capitalize;
}

Następnie po prostu zawiń wyrażenie (dla ex) w html:

<span class="capitalize">{{ uppercase_expression }}</span>

No js needed;)

 124
Author: TrampGuy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-05 13:56:05

Jeśli używasz Bootstrap , możesz po prostu dodać text-capitalize klasa pomocnicza: {]}

<p class="text-capitalize">CapiTaliZed text.</p>
 44
Author: minimalpop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 12:28:39

A nicer way

app.filter('capitalize', function() {
  return function(token) {
      return token.charAt(0).toUpperCase() + token.slice(1);
   }
});
 21
Author: Patrik Melander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-28 07:35:35

Jeśli zależy ci na wydajności, staraj się unikać używania filtrów AngularJS, ponieważ są one stosowane dwa razy na każde wyrażenie, aby sprawdzić ich stabilność.

Lepszym sposobem byłoby użycie pseudo-elementu CSS ::first-letter z text-transform: uppercase;. Tego nie można jednak używać na elementach wbudowanych, takich jak span, więc następną najlepszą rzeczą byłoby użycie text-transform: capitalize; na całym bloku, który zapisuje każde słowo wielkimi literami.

Przykład:

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

app.controller('Ctrl', function ($scope) {
   $scope.msg = 'hello, world.';
});
.capitalize {
  display: inline-block;  
}

.capitalize::first-letter {
  text-transform: uppercase;
}

.capitalize2 {
  text-transform: capitalize;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <b>My text:</b> <div class="capitalize">{{msg}}</div>
        <p><b>My text:</b> <span class="capitalize2">{{msg}}</span></p>
    </div>
</div>
 16
Author: Gregor Eesmaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-04 00:34:55

Podoba mi się odpowiedź od @ TrampGuy

CSS jest zawsze (cóż, nie zawsze) lepszym wyborem, więc: text-transform: capitalize; jest z pewnością drogą do zrobienia.

Ale co, jeśli treść jest wszystkie wielkie litery na początek? Jeśli spróbujesz text-transform: capitalize; Na treści takiej jak" FOO BAR", nadal pojawi się" FOO BAR " na ekranie. Aby obejść ten problem, możesz umieścić text-transform: capitalize; w css, ale także małe litery, więc:

<ul>
  <li class="capitalize">{{ foo.awesome_property | lowercase }}</li>
</ul>

Gdzie używamy klasy capitalize @ TrampGuy:

.capitalize {
  text-transform: capitalize;
}

Więc udając, że foo.awsome_property normalnie wydrukuje "FOO BAR", teraz wydrukuje żądany"Foo Bar".

 15
Author: Ryan Crews,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-07 22:30:18

Jeśli chcesz, aby każde słowo z łańcucha było pisane wielkimi literami (in progress - > in Progress), możesz użyć tablicy w ten sposób.

.filter('capitalize', function() {
    return function(input) {
        return (!!input) ? input.split(' ').map(function(wrd){return wrd.charAt(0).toUpperCase() + wrd.substr(1).toLowerCase();}).join(' ') : '';
    }
});
 13
Author: Naveen raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-20 05:44:49

Jeśli używasz Angular 4 + to możesz po prostu użyć titlecase

{{toUppercase | titlecase}}

Nie musisz pisać żadnych rur.

 8
Author: Abhishek Ekaanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 08:57:01

.capitalize {
  display: inline-block;
}

.capitalize:first-letter {
  font-size: 2em;
  text-transform: capitalize;
}
<span class="capitalize">
  really, once upon a time there was a badly formatted output coming from my backend, <strong>all completely in lowercase</strong> and thus not quite as fancy-looking as could be - but then cascading style sheets (which we all know are <a href="http://9gag.com/gag/6709/css-is-awesome">awesome</a>) with modern pseudo selectors came around to the rescue...
</span>
 7
Author: Philzen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-04 06:42:18

Dla Angular 2 i up, możesz użyć {{ abc | titlecase }}.

Sprawdź Angular.io API {[5] } dla pełnej listy.

 7
Author: windmaomao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-15 08:33:12

To jest inny sposób:

{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}
 6
Author: pallav deshmukh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-01 19:52:16

Dla AngularJS z meanjs.org, umieszczam własne filtry w modules/core/client/app/init.js

Potrzebowałem niestandardowego filtra do pisania wielkimi literami każdego słowa w zdaniu, oto jak to robię:

angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
    return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() :         ''}).join(" ");

}
});
Za zasługi dla funkcji mapy odpowiada @ Naveen raj
 3
Author: Maxim Mai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-27 16:09:11

Jeśli nie chcesz budować własnego filtra, możesz użyć bezpośrednio

{{ foo.awesome_property.substring(0,1) | uppercase}}{{foo.awesome_property.substring(1)}}
 2
Author: chhitij srivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 10:41:29

Aby dodać własne podejście do tej kwestii, sam użyłbym niestandardowej dyrektywy;

app.directive('capitalization', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attrs, modelCtrl) {

        modelCtrl.$parsers.push(function (inputValue) {

            var transformedInput = (!!inputValue) ? inputValue.charAt(0).toUpperCase() + inputValue.substr(1).toLowerCase() : '';

            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

            return transformedInput;
        });
    }
};

Po zadeklarowaniu możesz umieścić w swoim Html jak poniżej;

<input ng-model="surname" ng-trim="false" capitalization>
 1
Author: uk2k05,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-11 20:07:32

Zamiast tego, jeśli chcesz kapitalizować każde słowo zdania, możesz użyć tego kodu

app.filter('capitalize', function() {


return function(input, scope) {
if (input!=null)
input = input.toLowerCase().split(' ');

for (var i = 0; i < input.length; i++) {
   // You do not need to check if i is larger than input length, as your for does that for you
   // Assign it back to the array
   input[i] = input[i].charAt(0).toUpperCase() + input[i].substring(1);     


}
   // Directly return the joined string
   return input.join(' '); 
  }
});

I po prostu dodaj filtr "capitalize" do wejścia łańcucha, dla ex - {{name / capitalize}}

 1
Author: Akash Saxena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-20 06:07:58

W Angular 4 lub CLI możesz utworzyć taką rurę:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'capitalize'
})
/**
 * Place the first letter of each word in capital letters and the other in lower case. Ex: The LORO speaks = The Loro Speaks
 */
export class CapitalizePipe implements PipeTransform {
  transform(value: any): any {
    value = value.replace('  ', ' ');
    if (value) {
      let w = '';
      if (value.split(' ').length > 0) {
        value.split(' ').forEach(word => {
          w += word.charAt(0).toUpperCase() + word.toString().substr(1, word.length).toLowerCase() + ' '
        });
      } else {
        w = value.charAt(0).toUpperCase() + value.toString().substr(1, value.length).toLowerCase();
      }
      return w;
    }
    return value;
  }
}
 0
Author: eberlast,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-03 13:35:58
var app = angular.module("app", []);
app.filter('capitalize', function() {
    return function(str) {
        str = str.toLowerCase().split(" ");
        var c = '';
        for (var i = 0; i <= (str.length - 1); i++) {
            var word = ' ';
            for (var j = 0; j < str[i].length; j++) {
                c = str[i][j];
                if (j === 0) {
                    c = c.toUpperCase();
                }
                word += c;
            }
            str[i] = word;
        }
        str = str.join('');
        return str;
    }
});
 0
Author: murali2486,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-20 06:56:12

Angular ma 'titlecase', który pisze wielką literę w łańcuchu

Dla ex:

envName | titlecase

Zostanie wyświetlona jako EnvName

W przypadku stosowania z interpolacją, unikaj spacji typu

{{envName|titlecase}}

I pierwsza litera wartości envName zostanie wydrukowana wielkimi literami.

 0
Author: Vedha Peri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-25 15:47:56

Możesz dodać capitalize czas działania funkcji jako:

<td>{{lastName.charAt(0).toUpperCase()+ lastName.substr(1).toLowerCase()}}</td>
 -1
Author: Rahul Mankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 09:04:13

{{ uppercase_expression | capitaliseFirst}} powinno działać

 -1
Author: Hasan Shaik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 16:20:57