Ember: dynamically add input fields on click and read new data

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

When he clicks this button, he can enter the question in the new input field and press "Save". so I need that when saving it, the newly entered question should also appear next to the questions already shown.

So I have questions in the model

import DS from 'ember-data';

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

      

Then I'll add this to my controller and show 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 is 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'm trying to do here is that when I add a new question and click the Save button, I enter the entered question string into the questions array in my controller. And I expected the template to be re-rendered since it will change.

I can see that the new line has been successfully added, but it does not appear in the UI. Any idea why?

Use the latest ember (1.13) and ember-cli.

thank

+3


source to share


2 answers


You are using the wrong name for the alias property, use:

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

      

instead:



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

      

Because there model.challengeQuestions

is undefined

.

+2


source


It turned out to be pretty easy.

Instead

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

      



I had to write

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

      

Thank.

+2


source







All Articles