Reputation: 23
I have a searchfield with an action in EmberJS, which send data to an API and receives multiple items. Those items should be appended in form of a list and - and here's where I'm stuck - each have an action (in this case: add item to cart).
search.hbs
{{input valueBinding="model.domain"}}
<button {{action submitAction target="controller"}}>Check</button>
I have something like this in my search_controller.js
success : function (returnData) {
$("#result").append('<li >' +
returnData.domain.name + '</li>')
},
error : function (xhr, textStatus, errorThrown) {
},
})
What I want is the li have actions like
{{action 'addToCart'}}
which should call the action. But if I insert them like this
$("#result").append('<li ' + {{action "addToCart"}} + '>')
I get an Unexpected token { error. So my question is, is it possible to dynamically add HTML to a view with Ember-actions in it? I guess Embers view.appendTo is another possibility but I'm not quite sure how to use this here because now I have a for-loop which calls an action that generates one li - do I have to generate one view for every li?
Upvotes: 2
Views: 1627
Reputation: 11671
It is possible to dynamically add HTML to a rendered view. It is not possible to add dynamically a not compiled {{action}}
helper to a rendered view. If event handling is required along with the added HTML, then raw js events need to be used. Although it is possible to access ember objects from raw js (see this thread EmberJS Handling DOM Events using Views), i recommend for the issue mentioned to use ember object properties along with an {{each}}
helper.
http://emberjs.jsbin.com/vosaxeze/1/edit
hbs
<script type="text/x-handlebars" data-template-name="search">
<h2>this is search</h2>
<button {{action "submitAction" target="controller"}}>Check</button>
<ul id="result">
{{#each product in products}}
<li {{action "addToCart" product}} ><span>{{product.name}}</span></li>
{{/each}}
</ul>
</script>
js
App.SearchController = Ember.Controller.extend({
products:[],
actions:{
addToCart:function(product){
alert("addToCart:"+product.name);
},
submitAction:function(){
var self = this;
$.ajax({url:"",success:function(){
var products = self.get("products");
products.pushObject({id:1,name:"product1"});
products.pushObject({id:2,name:"product2"});
products.pushObject({id:3,name:"product3"});
products.pushObject({id:4,name:"product4"});
}});
}
}
});
Upvotes: 1