几个小时以来我一直在为这个问题苦恼,但现在我很确定这是 Angular2 的某个地方的问题。
场景:我从我的 PHP 中获取 JSON 中的 tinyint "isLiked": "1"
.由于 JSON,Javascript 将 tinyint 理解为字符串而不是 bool 值,所以我一直在使用 good ol' !!+isLiked
将其更改为 bool 值。
在我的 Angular2 模板中我需要做的:
<i class="glyphicon {{ (!(!!+post.isLiked) ) ? 'glyphicon-heart-empty' : 'glyphicon-heart' }}"></i>
这段代码曾经在带有 Underscore 模板的 Backbone 中完美运行。但是,Angular2 似乎做了一些改变 !!+"0"评估方式的事情!
在 Chrome 控制台中:
!!+"0"
返回 false
.
在 Backbone +下划线中:
<% !!+"0" %>
在模板中显示 false
.
在 Angular2 中:
{{ !!+"0" }}
在模板中显示 true
.
这是它的 Playground http://plnkr.co/E3YGYeQ5ZZIRh8JxsUN6 .
false
来自一个简单的 Javascript document.write(!!+"0")
在 index.html 中,在 Angular 执行任何操作之前。
true
在里面src/app.ts
模板。
我错过了什么吗?
最佳答案
Angular 模板语法不支持完整的 JavaScript 语法。 只需将您的代码移动到一个函数中并调用它即可
<i class="glyphicon {{ truthyCheck(+post.isLiked) ? 'glyphicon-heart-empty' : 'glyphicon-heart' }}">
class MyComponent {
trutyCheck(value):boolean {
return !(!!+post.isLiked) ;
}
}
另见
- https://angular.io/docs/ts/latest/guide/template-syntax.html#!#template-expressions
- https://angular.io/docs/ts/latest/guide/template-syntax.html#!#template-statements
关于javascript - double not (!!+) 的 Angular2 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303715/