简体   繁体   English

AngularJs,ng-if如何更改文本?

[英]AngularJs, ng-if to change text?

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的在线书店

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>; 形式为三元运算符:( (expression)?<true clause>:<false clause>; and is equal to: 并且等于:

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. 这可以通过调用范围函数或对变量应用过滤器来按预期转换它来完成。

Use a filter! 使用过滤器!

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

Then: 然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM