Ember: Adding input fields dynamically on click and reading the new data

你。 提交于 2019-12-21 19:56:47

问题


I have a page where i show user couple of questions and provide input field for answers. Also i have a button add a question.

On clicking this, he can enter a question in the new input field and click save. so what i need is that, when he save, the newly entered question should also show up near the already shown questions.

So i have the questions in the model

import DS from 'ember-data';

export default  DS.Model.extend({
  challengeQuestions: DS.attr()
});

Then i alias this in my controller and show the two questions from the template.

import Ember from "ember";

export default Ember.Controller.extend({

   addQuestion : false,

   questions : Ember.computed.alias('model.challengeQuestions'),

   actions : {
     postAnswer: function(){
        alert('prepare post data');
     },

     addQuestion: function(){
       this.set('addQuestion', true);
     },

     saveQuestion: function() {
       var que = this.get('newQuestion');
       this.get('questions').push(que);
       this.send('cancel');
     },

     cancel: function(){
       this.set('addQuestion', false);
     }
   }
});

And below goes my template..

{{log questions}}
{{#each question in questions}}
    <div>
        <span>{{question}} : </span>
        {{input placeholder="your answer"}}
    </div>
{{/each}}


<br><br>
{{#if addQuestion}}
    {{input placeholder="Enter your question" value=newQuestion}}
    <br>
    <button {{action "saveQuestion"}}>Save</button> <button {{action      "cancel"}}>cancel</button>
{{else}}
    <button {{action 'addQuestion'}}>Add manual Question</button>
{{/if}}

<br><br>
<button {{action 'postAnswer'}}>Submit</button>

So what i am trying to do here is that, when i add a new question and click on save button, i push the entered question string to the questions array in my controller. And i was expecting that the template would re-render since it is modified.

I can see that the new string is being successfully added but it doesnt show up on the UI. Any idea why?

Am using latest ember(1.13) and ember-cli.

Thanks


回答1:


It turned out be pretty easy..

Instead of

this.get('questions').push(que);

i had to write

this.get('questions').pushObject(que);

Thanks.




回答2:


You're using wrong name for alias property, use:

questions: Ember.computed.alias('model.securityQuestions')

instead of:

questions: Ember.computed.alias('model.challengeQuestions')

Because model.challengeQuestions is undefined.



来源:https://stackoverflow.com/questions/31743116/ember-adding-input-fields-dynamically-on-click-and-reading-the-new-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!