尝试使用ng-model用破折号替换空格 [英] Trying to replace spaces with dashes using ng-model

查看:88
本文介绍了尝试使用ng-model用破折号替换空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AngularJS的新手,正在尝试创建一个简单的应用程序,该应用程序允许我将文件上传到我的Laravel驱动的网站.我希望表单向我显示上传项目的预览.因此,我正在使用ng-model来实现这一目标,而我偶然发现了以下内容:

I'm new to AngularJS and trying to create a simple app that will allow me to upload files to my Laravel driven website. I want the form to show me the preview of what the uploaded item will look like. So I am using ng-model to achieve this and I have stumbled upon the following:

我有一些基本的Bootstrap样式输入,并且我在AngularJS模板中使用自定义括号(因为正如我所提到的,我在Laravel的刀片系统中使用了Laravel).而且我需要从输入中删除空格(在输入时),并用破折号代替它们:

I have an input with some basic bootstrap stylings and I am using custom brackets for AngularJS templating (because as I mentioned, I am using Laravel with its blading system). And I need to remove spaces from the input (as I type it) and replace them with dashes:

<div class="form-group"><input type="text" plaeholder="Title" name="title" class="form-control" ng-model="gnTitle" /></div>

然后我有这个:

<a ng-href="/art/[[gnTitle | spaceless]]" target="_blank">[[gnTitle | lowercase]]</a>

我的app.js看起来像这样:

And my app.js looks like this:

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

app.config(function($interpolateProvider){
    $interpolateProvider.startSymbol('[[').endSymbol(']]');
});

app.filter('spaceless',function(){
    return function(input){
        input.replace(' ','-');
    }
});

我收到以下错误: TypeError:无法读取未定义的属性替换"

I get the following error: TypeError: Cannot read property 'replace' of undefined

我知道我需要在过滤值之前先定义它,但是我不确定在哪里准确定义它.而且,如果我定义了它,我也不希望它更改我的占位符.

I understand that I need to define the value before I filter it, but I'm not sure where to define it exactly. And also, if I define it, I don't want it to change my placeholder.

推荐答案

过滤器中缺少一些内容.首先,您需要返回新字符串.次要,正则表达式不正确,应使用全局修饰符以替换所有空格字符.最后,您还需要检查是否已定义字符串,因为最初的模型值可以为undefined,因此未定义的.replace会引发错误.

There are few things missing in your filter. First of all you need to return new string. Secondary, regular expression is not correct, you should use global modifier in order to replace all space characters. Finally you also need to check if the string is defined, because initially model value can be undefined, so .replace on undefined will throw error.

一起:

app.filter('spaceless',function() {
    return function(input) {
        if (input) {
            return input.replace(/\s+/g, '-');    
        }
    }
});

这篇关于尝试使用ng-model用破折号替换空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆