我正在尝试在 embers js 中使用 if 条件。但值(value)没有正确传递。
如果条件
{{#each item.model }}
{{#ifCond item.title Raja}}
<div>equal to</div>
{{else}}
<div>not equal to</div>
{{/ifCond}}
{{/each}}
这是我的 HandleBar
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
alert(v1);
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
我的问题是警报显示值item.title
但我想要有值(value)的样本。
这是我的 Json
posts = [{
title: "sample",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
最佳答案
可以使用助手中的当前上下文来评估值。
示例,
http://emberjs.jsbin.com/dixokezafe/1/edit?html,js
hbs
<script type="text/x-handlebars" data-template-name="index">
{{#each model }}
{{#ifCond title Raja}}
<div>equal to</div>
{{else}}
<div>not equal to</div>
{{/ifCond}}
{{/each}}
<button {{action "addObject"}}> add random object</button>
js
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts;
}
});
App.IndexController = Em.ArrayController.extend({
actions:{
addObject:function(){
this.get("model").pushObject({
title: Math.floor(Math.random()*2)===0?"Raja":"something else",
body: "James Coglan wrote a lengthy article about Promises in node.js."
});
}
}
});
var posts = [{
title: "sample",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
},
{
title: "Raja",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
var _v1 = Em.get(this,v1);
var _v2 = Em.get(this,v2);
v1 = Em.isEmpty(_v1)?v1:_v1;
v2 = Em.isEmpty(_v2)?v2:_v2;
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
似乎无法注册绑定(bind)助手并以 block 形式使用它。查看一些包含解决此问题的有趣方法的链接。
http://discuss.emberjs.com/t/a-way-to-let-users-define-custom-made-bound-if-statements/2583
https://gist.github.com/slindberg/9924116
http://paarsgames.nl/2014/02/02/creating-your-own-custom-handlebars-bounded-ifs-in-ember/
关于javascript - 如果条件未在 ember 中传递正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041859/