/ emberjs

Ember.js: Create link to div on another page using link-to helper

In simple html pages, we can easily create link to div tag or any other tag on same page and even on different pages.

For example:

Heading Text

Refer it as:

Link text

Now how we can achieve it in Ember.js using {{link-to}} helper?

Lets take as example:

-> Consider we have a page "/faq" and it has following content:

faq.hbs

..

What kinds of items can be donated?

..

-> Now we want to visit page "faq" and scroll it down to the above question.

-> Simply, we can achieve it using

Question

But, it will not work as ember link. Like if you are using your ember app as web-app on mobile then it will open in mobile-browser and not in your mobile web-app.

-> so we can do it using queryParams

  1. In "faq" controller:
import Ember from 'ember';
export default Ember.Controller.extend({
  questionAnchor: null,

  actions: {
    displayQuestion: function() {
      var question = this.get("questionAnchor");
      if(question) {
        var scrollOffset = Ember.$("#" + question).offset().top;

        Ember.$('html, body').animate({
          scrollTop: scrollOffset - 70
        }, 'fast');
      }
      return false;
    }
  }
});
  1. In "faq" route:
import Ember from 'ember';
export default Ember.Route.extend({
  queryParams: {
    questionAnchor: null
  },

  setupController: function(controller, context, params){
    controller.set('questionAnchor', params.queryParams.questionAnchor);
  }
});
  1. In "faq" view
import Ember from 'ember';
export default Ember.View.reopen({
  didInsertElement: function() {
    this._super();
    
    Ember.run.scheduleOnce('afterRender', this, function(){
      var controller = this.get('controller');
      if(controller && controller.questionAnchor) {
        controller.send('displayQuestion');
      }
    });
  },
});
  1. Now add link as follows
{{#link-to 'faq' (query-params questionAnchor="question1") classNames="info_link"}}
  Show Question
{{/link-to}}

That's it!!

Now when we click on "Show Question" link, it will go to route and in setupController hook,

it will set value of controller property (id of question link, we want to visit).

After that, when the view is rendered (as we need to locate the div with question-id we are using afterRender event),

it will call displayQuestion action and scroll page to that question.

So with the use of queryParams and afterRender event of ember-view, we have achieved it.

Thanks..!!

Swati Jadhav

I am a Rubyist, ROR developer, passionate about change and trying new things, both professionally and in general with life. Currently, working on Ember.js applications and fasci...

Read More