<form role="form" method="POST" action="{{ url('/roles/save') }}" data-ng-app="">
<div class="form-group">
<label>Page-Title:</label>
<input type="text" required value="" data-ng-model="title" name="page_title" class="form-control">
</div>
<div class="form-group">
<label>Page-Alias:</label>
<input type="text" value="@{{ title }}" name="page_alias" class="form-control">
</div>
我是角色新手并使用简单的数据绑定,因此无论何时用户输入页面标题,别名都会自动生成,但我想识别空格并用“ - ”(短划线)替换它们。例如:每当用户进入主页时,我希望别名为Home-Page,如果它是主页,则更好。 我试过这个
<input type="text" value="@{{title.replace(/-/g, ' ');}} name="page_alias" class="form-control">
但它不起作用。
答案 0 :(得分:4)
<强> JS 强>
angular.module('app')
.filter('slugify', function() {
return function(input) {
input = input || '';
return input.replace(/ /g, '-').toLowerCase();
}
});
<强> HTML 强>
<input type="text" value="@{{ title | slugify }}" name="page_alias" class="form-control">
我在替换后添加toLowerCase
来实现此目的。
答案 1 :(得分:2)
您可以为模板创建过滤器:
.filter('replacementFilter', function() {
return function(input) {
return input.replace(/ /g, '-');
}
});
并使用它:
<input type="text" value="@{{ title | replacementFilter }}" name="page_alias" class="form-control">
点击这里:
答案 2 :(得分:0)
你可以用两种方式做:一个使用replace within the expression
,另一个使用超棒的角度过滤器。
<input type="text" value="@{{ title.replace('-',' ')}}" name="page_alias" class="form-control">
<input type="text" value="@{{ title | replaceSpaceWithDash : '-'}}" name="page_alias" class="form-control">
app.filter("replaceSpaceWithDash", function() {
return function(data, delimiter) {
return data.replace(/\s/g,delimiter);
}
});
您可以将delimiter
更改为传递给replaceSpaceWithDash
过滤器的任何内容。目前正在通过-
,您可以根据需要稍后进行更改。
要将其设为小写,只需使用内置过滤器| lowercase
所以它会变成:
value="@{{ title | replaceSpaceWithDash : '-' | lowercase }}"
答案 3 :(得分:0)
如果您想要文本框的-blur,您可以这样使用:
<input type="text" required value="" data-ng-model="title" ng-blur="removeSpaces(title)" name="page_title" class="form-control">
JS:
angular.module('app', [])
.controller('myController', function($scope) {
$scope.removeSpaces = function(text) {
$scope.title = text.split(' ').join('-').toLowerCase();
}
});
<强>更新强>
<input type="text" required value="" data-ng-model="title" ng-blur="removeSpaces(title)" name="page_title" class="form-control">
<input type="text" value="@{{ alias }}" name="page_alias" ng-modal="alias" class="form-control">
JS:
angular.module('app', [])
.controller('myController', function($scope) {
$scope.removeSpaces = function(text) {
$scope.alias = text.split(' ').join('-').toLowerCase();
}
});