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

时间:2018-02-20 15:25:23

标签: angularjs filter 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>

2 个答案:

答案 0 :(得分:6)

可根据您的需求进行定制。

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

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

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

  };
}]);

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

&#13;
&#13;
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());

  };
}]);
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您使用的是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;
 }
}

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

@NgModule({
  declarations: [
  AppComponent,
   HumanizePipe,
...

像这样使用它

<label>{{CamelCase | humanize}}</label>

它将显示“骆驼套”

Adapted from here