Populate the select field from collection and filt

2019-03-02 15:39发布

问题:

I am a new guy in Meteor. I have select box which i want to populate from the mongo collection itself.I tried doing this as below but doesn't work

<template name="clist">

<div class="input-field">
 <select>
   <option value="" disabled selected>Choose your option</option>
    {{#each company}}
      <option>{{ccategory}}</option>
    {{/each}}
 </select>
</div>

<ul class="collection" id="listings">
{{#each company}}
 <li>
  {{> employees}}
</li>
{{/each}}

</template>

And also i want to filter the data in mytemplate according to the value selected in the dropdownlist. Please help me iam stuck in this.

this is exactly what i have now but the problem is the dropdownlist is populating based on the results of all the listings not directly from the schema and is repetitive of all values. and i am using the same returning helper for both these values like return company.find(). Please help me

回答1:

Well in order to populate the select, you should change the {{#each}} down to the select, like this.

<select>
  <option disabled selected>Choose option</option>
{{#each company}}
  <option>{{category}}</option>
{{/each}}
</select>

Because if you put the {{#each}} at the top of the <select> tag meteor will create 1 select for each company.

And the company helper should be simple like a simple return company.find();

Now if you want to filter, there are many options to accomplish this, one could be this.

I like to use ReactiveDict(); , so i will use on this example.

Install it meteor add reactive-dict

Template.example.onCreated(function(){
 var self = this;

 self.example = new ReactiveDict();

self.example.setDefault( 'valueToFilter' , null);
});

Now on some event like change, do the following.

Template.example.events({
 'change select' : function( event, template ) {

   var instance = Template.instance();

   instance.example.set( 'valueToFilter' event.target.value ); //or use $('select').val()  whatever you like to take the value;
  }
})

Now show the results.

Template.example.helpers({

 showSelectedValues : function(){

  var instance = Template.instance();

  return Companies.find( { name : instance.example.get( 'valueToFilter' )} );
 }
})

This should give you a big picture, good luck!