javascript AngularJs,ng-if 更改文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23848608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:41:03  来源:igfitidea点击:

AngularJs, ng-if to change text?

javascriptangularjs

提问by PrimeLens

I'm given the following code

我得到了以下代码

 <h2>{{ownername}} Online Bookshop</h2>
 <input placeholder="type your name" ng-model="ownername" >

Which outputs 'Online Bookshop'

输出“在线书店”

and if I input 'Fred' it outputs 'Fred Online Bookshop'

如果我输入“Fred”,它会输出“Fred Online Bookshop”

Without using jQuery, and doing things the angular way, how would I change the code so that a possessive apostrophe and the letter s were added when input is not empty?

如果不使用 jQuery,并以有角度的方式做事,我将如何更改代码,以便在输入不为空时添加所有格撇号和字母 s?

EG

例如

Online Bookshop when input is empty, and

输入为空时的在线书店,以及

Fred's Online Bookshop when input contains 'Fred' string

当输入包含“Fred”字符串时,Fred 的在线书店

回答by sabhiram

Remember that the scope is just a place where you can evaluate things. So thats exactly what we can do. The ?is a ternary operator of the form: (expression)?<true clause>:<false clause>;and is equal to:

请记住,范围只是您可以评估事物的地方。所以这正是我们能做的。的?是以下形式的三元运算符:(expression)?<true clause>:<false clause>;并且等于:

if(expression) { <true clause>; }
else { <false clause>; }

Modified code:

修改后的代码:

<h2>{{ ownername.length ? ownername + "'s " : "" }}Online Bookshop</h2>
<input placeholder="type your name" ng-model="ownername" >

Edit:Even though this works, its probably better as others point out to hide the logic from the view. This can be done by calling a scope function, or applying a filter to the variable to transform it as expected.

编辑:尽管这有效,但正如其他人指出的那样,从视图中隐藏逻辑可能会更好。这可以通过调用作用域函数或将过滤器应用于变量以按预期转换它来完成。

回答by Joe

Use a filter!

使用过滤器!

app.filter('possessive', function() {
  return function(val) {
    if (!val) return '';
    return val + '\'s';
  };
});

Then:

然后:

<h2>{{ ownername | possessive }} Online Bookshop</h2>