lch
lch

Reputation: 4951

Dynamic linkTo with a plain anchor tag in Ember.js

export default Ember.Component.extend({
  tagName: '',

  actions: {
    checkUrl(post) {
      if(!Ember.get(post, 'property')) {
        event.preventDefault();
        // show modal dialog
      }
    }
  }
});

<a href="{{post.otherUrl}}" {{action 'checkUrl' post preventDefault=false}}>URL</a>

The above component with generate a link to open 'otherUrl'. if the post object doesn't contain 'otherUrl' i will a show a modal dialog

Dialog Template (Different Component)

<p>No Link Found. Go to <a class="post-link">post</a> and add otherUrl</p>

I want to point the 'post-link' anchor tag to different 'post' route each time like 'post/1', 'post/2' etc basing the post user clicked in the first place. Should i recompile or rerender modal dialog template for this. One way to do this manipulate DOM and add href for that 'post-link' basing post user click. But the resultant link will trigger the full page load instead of route. Could someone guide me on how to achieve this

Upvotes: 0

Views: 504

Answers (1)

mwp
mwp

Reputation: 8477

Instead of linking to a URL that may be invalid and preventing the transition if it is, just render a different anchor tag:

{{#unless post.property}}
  <a href={{post.otherUrl}}>URL</a>
{{else}}
  <a href="#" {{action 'showModal' post}}>URL</a>
{{/unless}}

Let the showModal action bubble up to (or even better, pass a closure action from) the controller where the modal is rendered. Set the passed post to a property on that controller, and pass that property to the modal component to be rendered. If you can't link directly to the post from the modal, you can have another action that closes the modal and transitions. Something like this:

// app/controllers/posts.js
export default Ember.Controller.extend({
  selectedPost: null,

  actions: {
    showModal(post) {
      this.set('selectedPost', post);
      // TODO: show the modal
    },

    editPost(post) {
      // TODO: hide the modal
      this.transitionToRoute('post', post);
    }
  }
});

// app/templates/posts.hbs
{{#modal-dialog}}
  <p>No Link Found. Go to <a href="#" {{action 'editPost' selectedPost}} class="post-link">post</a> and add otherUrl</p>
{{/modal-dialog}}

Upvotes: 2

Related Questions