Meteor:从动态过滤的下拉列表中选择选项

时间:2015-03-21 13:50:27

标签: javascript jquery meteor

Meteor dynamically filter dropdown when another dropdown is selected类似的情况:我可以根据选择#1填充选择#2中的项目。

但是我无法以编程方式将选择#2的特定选项设置为选中 - 至少不是在选择#1的更改事件之后 - 因为项目尚未填充。

html的:

<head>
  <title>Dropdown</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">

  <ul>
    {{#each products}}
      <li>{{name}}</li>
    {{/each}}
  </ul>

  <select id="main-cat">
    <option>Select One</option>
    {{#each categories}}
      <option value="{{name}}">{{name}}</option>
    {{/each}}
  </select>

  <select id="sub-cat">
    <option>Select One</option>
    {{#each subCategories}}
      <option value="{{name}}">{{name}}</option>
    {{/each}}
  </select>

</template>

的.js:

if (Meteor.isClient) {

  Template.hello.helpers({
    products: function() {
      return Products.find();
    },

    categories: function() {
      return Categories.find();
    },

    subCategories: function() {
      return Session.get("selectedMainCat") && Categories.findOne({ name: Session.get("selectedMainCat") }).subCategories;
    }
  });


  Template.hello.events({
    "click li": function () {
      $("#main-cat").val(this.category);
      Session.set("selectedMainCat", $("#main-cat").val()); // now #sub-cat should be filled because of subCategories helper above
      $("#sub-cat").val(this.subCategory); // this should select the appropriate subcat, but doesn't. apparently it's slightly too early...
    },

    "change #main-cat": function() {
      Session.set("selectedMainCat", $("#main-cat").val());
    }

  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    Categories.remove({});
    Categories.insert( 
      {
        name: "MainCategory1",
        subCategories: [
          {name: "SubCategory1.1"},   
          {name: "SubCategory1.2"}
        ]
      }
    );
    Categories.insert( 
      {
        name: "MainCategory2",
        subCategories: [
          {name: "SubCategory2.1"},   
          {name: "SubCategory2.2"}
        ]
      }
    );

    Products.remove({});
    Products.insert({
      name: "myProduct1",
      category: "MainCategory2",
      subCategory: "SubCategory2.2"
    });
    Products.insert({
      name: "myProduct2",
      category: "MainCategory1",
      subCategory: "SubCategory1.2"
    });

  });
}

collection.js:

Products = new Mongo.Collection('products');
Categories = new Mongo.Collection('categories');

0 个答案:

没有答案