19

How can I set custom data- attribute on the {{#linkTo}} helper? I want use this:

{{#linkTo "foo" data-toggle="dropdown"}}foo{{/linkTo}}

and the result should look like this:

<a id="ember323" class="ember-view active"  data-toggle="dropdown" href="#/foo/123">foo</a>

but it looks like:

<a id="ember323" class="ember-view active"  href="#/foo/123">foo</a>

How can I do this?

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
Lux
  • 17,835
  • 5
  • 43
  • 73

2 Answers2

29

A way you could do this is to extend your Ember.LinkComponent to be aware of the new attribute:

Ember.LinkComponent.reopen({
  attributeBindings: ['data-toggle']
});

And then you can use it in your {{#link-to}} helper:

{{#link-to 'foo' data-toggle="dropdown"}}Foo{{/link-to}}

This will result in:

<a id="ember262" class="ember-view active" href="#/foo" data-toggle="dropdown">Foo</a>

And since attributeBindings is an array your can put multiple attributes there that you might need:

attributeBindings: ['data-toggle', 'foo', 'bar']

Hope it helps.

Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
intuitivepixel
  • 23,302
  • 3
  • 57
  • 51
  • where do you put this code? I'm using ember-cli and haven't learned yet where a file like this should go. Also, is {{#linkTo}} a custom helper you made, or did you mean to write {{#link-to}}? – redOctober13 Sep 02 '14 at 16:10
  • @redOctober13 Thanks, I corrected my answer `link-to` is now the new helper and is included out of the box. As for ember-cli it picks up files by file name, so a view should live in the `views` directory. – intuitivepixel Sep 03 '14 at 21:43
  • Updated to from `LinkView` to `LinkComponent`. As pointed out in an other answer, in Ember 2.0+ views have been deprecated. Use `Ember.LinkComponent.reopen` instead. – Stéphane Bruckert Nov 27 '18 at 12:18
9

@intuitivepixel

Thanks

U helped a lot. With that Information I've played arround with the LinkView and was able to find a generic solution:

Em.LinkView.reopen({
    init: function() {
        this._super();
        var self = this;
        Em.keys(this).forEach(function(key) {
            if (key.substr(0, 5) === 'data-') {
                self.get('attributeBindings').pushObject(key);
            }
        });
    }
});
Lux
  • 17,835
  • 5
  • 43
  • 73
  • 2
    This solution has been more or less added to the official documentation: http://guides.emberjs.com/v1.10.0/templates/binding-element-attributes/#toc_adding-data-attributes – Jason Jun 05 '15 at 21:29
  • Weird. I wonder why data attributes are blacklisted by default. –  Aug 20 '15 at 17:16
  • 6
    In Ember 2.0+ Views have been deprecated. Use `Ember.LinkComponent.reopen` instead. – Tyler Oct 22 '15 at 21:28
  • it would be a good idea to check programmatically which version of Ember is being used, like checking if `Ember.LinkView` is undefined and then using `Ember.LinkComponent` instead. this would make it backwards-compatible with Ember 1.x –  Nov 12 '15 at 18:18