Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

ember.js - How to get Emberjs generated element id in controller

I would like to get the Ember generated id of an element.

{{#each}}
<div>
 <h1>{{MyComponent}}</h1>
</div>
{{/each}}

which render something like:

<div id="ember180" class="ember-view">
 <h1>My Component here</h1>
</div>

I need to get the id of each div element inside a controller. If I've to use custom id then how can I create custom id using ember view.

And how can I identify each div element by its id inside controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure exactly what you mean, but I can answer:

And how can I identify each div element by its id inside controller?

Working Example Look at the console.log to see the element id, and then use Google Chrome or Firebug to inspect the component element to see that the id is the same.

App.ItemOneComponent = Ember.Component.extend({
  didInsertElement: function(){
    console.log('element id: ' + this.elementId);
  }
});

this inside the component is the component, and elementId gets the id of the div (or different tag if you use tagName inside the component).

If you want to select the component with JQuery, use: this.$() inside of the component.

Now here is where I don't know what you need so I'm going to throw out a few suggestions. If you need to know the ids of every component from the controller, I would recommend passing in an array sitting on the controller to the component. In your didInsertElement, add the elementId or the jQuery object to the array.Here is what I mean

App.IndexController = Ember.ArrayController.extend({
  componentIds: []  
});

App.ItemOneComponent = Ember.Component.extend({
  didInsertElement: function(){
    this.get('array').pushObject(this.elementId);
  }
});

And your component passes the property in: {{item-one array=controller.componentIds}}

You could also send the component's id or jQuery object via an action with this.sendAction('actionName', componentId) and have an action defined on your controller that takes one parameter (ie the componentId or the jQuery object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...