admin管理员组文章数量:1193749
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'
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?
EG
Online Bookshop when input is empty, and
Fred's Online Bookshop when input contains 'Fred' string
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'
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?
EG
Online Bookshop when input is empty, and
Fred's Online Bookshop when input contains 'Fred' string
Share Improve this question edited Jun 7, 2019 at 9:22 R3tep 12.9k10 gold badges51 silver badges76 bronze badges asked May 24, 2014 at 18:58 PrimeLensPrimeLens 2,6974 gold badges24 silver badges28 bronze badges2 Answers
Reset to default 21Remember 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:
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>
本文标签: javascriptAngularJSngif to change textStack Overflow
版权声明:本文标题:javascript - AngularJs, ng-if to change text? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738491098a2089709.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论