Inserting a Model Property into an Img Element URL in Ember

守給你的承諾、 提交于 2019-12-22 04:05:55

问题


I have a Model with an image_id property. I have a View for that Model that contains an image element. I need to insert the id into the image element's src property to complete the URL of the image so that I'm effectively doing this:

<img src="news + newsItem.imageID + .jpg"></img> 

My first attempt used a Handlebars helper:

<img src="news{{newsImageURL newsItem.imageID}}.jpg"></img> 

But this also inserted Metamprph script tags around it:

<img url="&lt;script id='metamorph-10-start' type='text/x-placeholder'&gt;&lt;/script&gt;news/7.jpg&lt;script id='metamorph-10-end' type='text/x-placeholder'&gt;&lt;/script&gt;" alt="" class="content-image news-media" /></a>

So I've looked at using bindAttr, however as I need to transform the image_id value(by prepending and appending the rest of the path), this doesn't seem like a solution either.


回答1:


There are 2 possibilities:

1- Declare the image path as computed property on your model. If you don't like that, you could declare it also in your ObjectController backing this template:

The Template:

// until 1.0 RC7
<img {{bindAttr src="newsItem.imagePath"}}></img> 
// from 1.0 final (the above one is deprecated)
<img {{bind-attr src=newsItem.imagePath}}></img> 

The Model:

App.NewsItem = DS.Model.extend({
  imageID: DS.attr('string'),
  imagePath: function() {
    return "/assets/news/"+this.get("imageID")+".jpg";
  }.property('imageID')
});

2- If you do not need the binding in 1 (i guess your id won't change) and use the unbound helper, which does not result in script tags:

<img src="news{{unbound newsItem.imageID}}.jpg"></img> 



回答2:


You can make bindAttr reference a computed property and build your string there.



来源:https://stackoverflow.com/questions/15624593/inserting-a-model-property-into-an-img-element-url-in-ember

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!