使用angularjs过滤器拆分带空间的驼峰案例字符串

hab*_*bib 3 filter angularjs angularjs-filter

我想将camel case字符串拆分为常规表单,并希望使用自定义过滤器.

<select class="form-control" ng-model="emailsettingType" ng-change="emailsettingTypeChange()" name="emailsettingType" ng-required="true">
<option ng-repeat="opt in emailtypesforuser">{{opt|splitCamelCase}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

The*_*One 8

如果您使用的是 Angular 2 +,则可以创建自定义管道:

创建humanize.ts:

import {Pipe} from ‘angular2/core’;

@Pipe({
name: ‘humanize’
})

 export class HumanizePipe {
 transform(value: string) {
 if ((typeof value) !== ‘string’) {
 return value;
 }
 value = value.split(/(?=[A-Z])/).join(‘ ‘);
 value = value[0].toUpperCase() + value.slice(1);
 return value;
 }
}
Run Code Online (Sandbox Code Playgroud)

在 app.module.ts -> 声明中添加一个条目

@NgModule({
  declarations: [
  AppComponent,
   HumanizePipe,
...
Run Code Online (Sandbox Code Playgroud)

像这样使用它

<label>{{CamelCase | humanize}}</label>
Run Code Online (Sandbox Code Playgroud)

它将显示“骆驼案例”

改编自这里


Pez*_*ter 6

这可以定制,以满足您的需求.

.filter('splitCamelCase', [function () {
  return function (input) {

    if (typeof input !== "string") {
      return input;
    }

    return input.split(/(?=[A-Z])/).join(' ');

  };
}]);
Run Code Online (Sandbox Code Playgroud)

如果您不希望每个第一个字符都大写,请删除toUpperCase().

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

app.controller('MainCtrl', function($scope) {
  $scope.emailtypesforuser = ['OneType', 'AnotherType', 'thisType', 'thatType', 'THatTypppeRRR'];
});

app.filter('splitCamelCase', [function () {
  return function (input) {

    if (typeof input !== "string") {
      return input;
    }

    return input
     .replace(/([A-Z])/g, (match) => ` ${match}`)
     .replace(/^./, (match) => match.toUpperCase());

  };
}]);
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.angularjs.org/1.5.4/angular.js"></script>
    <!-- By setting the version to snapshot (available for all modules), you can test with the latest master version -->
    <!--<script src="https://code.angularjs.org/snapshot/angular.js"></script>-->
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p ng-repeat="opt in emailtypesforuser">{{opt|splitCamelCase}}</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)