Creating a dynamic string with bindAttr

2019-05-28 19:50发布

I'd like to create a dynamic classname on an object with a value I'm getting from my model. One of the keys is named provider which contains either "twitter" or "facebook". What I'd like to do is to prepend the string "icon-" to the provider so that the resulting class is icon-twitter or icon-facebook.

This is the code that I've got now.

<i {{bindAttr class=":avatar-icon account.provider"}}></i>

Ember offers a way to include a static string within the attribute by prepending : to it. You can see that I'm also adding a class called avatar-icon in this example. I've already tried :icon-account.provider which simply resulted in the literal string "icon-account.provider".

RESPONSE Nice one. I'm working on a solution similar to your answer right now. Question though: this view will be used within the context of an each loop. How would I pass in the current item to be used within the view? I have this right now:

{{#each account in controller}} {{#view "Social.AccountButtonView"}} <i {{bindAttr class="account.provider"}}></i> {{/view}} {{/each}}

Is it possible to just do this:

{{#view "Social.AccountButtonView" account="account"}} ?

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-28 20:31

I have previously stated that attributeBindings would be a suitable solution for this, but I was mistaken. When binding the class attribute of a given View, as pointed out, you should use classNames or classNameBindings. Please refer to the sample below:

App.ApplicationView = Em.View.extend({
    provider: 'Facebook',
    classNameBindings: 'providerClass',
    providerClass: function() {
        return 'icon-avatar icon-%@'.fmt(this.get('provider').toLowerCase());
    }.property('provider')
});

This will render the following HTML:

<div id="ember212" class="ember-view icon-avatar icon-facebook">
    <h1>App</h1>    
</div>

Here's a fiddle: http://jsfiddle.net/schawaska/HH9Sk/

(Note: The fiddle is linking to a version of Ember.js earlier than RC)

查看更多
登录 后发表回答