2013-08-26 64 views
1

我在使用ember时难以显示select2组件上显示的选定选项。这是我的控制器看起来像:在ember.select中动态设置选定选项使用select2 lib

AS_ANALYTICS.Exercise = Ember.Object.extend({ 
    id: null, 
    name: null 
}); 

AS_ANALYTICS.SelectedExercise = Ember.Object.extend({ 
    exercise: null, 
    changed:function(){ 
     if(this.exercise.id!==null){ 

     } 
    }.observes('exercise') 
}); 

AS_ANALYTICS.selectedExercise = AS_ANALYTICS.SelectedExercise.create(); 

AS_ANALYTICS.ExerciseController = Ember.ArrayController.create({ 
    content:[], 

    setContent:function(exercises){ 
     //each array controller has content property by default 
     //selects seems to only use this property for some reason 
     this.set('content',exercises); 
     if(exercises.length==1){ 
      //SOMETHING IS OFF HERE! 
      console.log(AS_ANALYTICS.ExerciseController.objectAt(0).get('id')); 
      AS_ANALYTICS.selectedExercise.set('exercise',AS_ANALYTICS.ExerciseController.objectAt(0)); 
      $('#exerciseId').select2({ 
       width:'300px' 
      }).select2('val',AS_ANALYTICS.ExerciseController.objectAt(0).get('id')); 
     } 
    }, 

    populateExercisesForClient:function(customerId){ 
     var self = this; 
     jQuery.getJSON(AS.baseURL+'analytics/listCustomerExercisesJson',{"id":customerId}, function(json) { 
      var exercises = [], i = 0,len = json.length; 

      for(;i<len;i++){ 
       exercises.push(AS_ANALYTICS.Client.create({"id":json[i].id,"name":json[i].name})); 
      } 
      self.setContent(exercises); 
     }); 
    } 
}); 

我打电话populateExercisesForClient,这使得一个Ajax请求来填充内容。当我点击select2组件时,在下拉菜单中,我可以看到该选项已突出显示,但不知何故,选择默认显示'请选择...',而不是所选选项的文本。

我的看法代码:

AS_ANALYTICS.Select2SelectView = Ember.Select.extend({ 
    prompt: 'Please select...', 
    classNames: ['input-xlarge'], 

didInsertElement: function() { 
    var elem = this.$(); 
    Ember.run(function() { 
     Ember.run.scheduleOnce('afterRender', this, function(){ 
      elem.select2({ 
       width:'300px' 
      }); 
     }); 
    }); 
}, 

willDestroyElement: function() { 
    var elem = this.$(); 
    elem.select2("destroy"); 
}}); 

您的帮助将不胜感激。谢谢。

UPDATE: enter image description here 这是我讲的,则该选项被选择,但不列入文本上出现的选择上面,甚至当我使用的选择视图后“buuda”建议,仍然同样的问题!

回答

2

我写了一个select2视图,它扩展了Ember.Select。你可以找到要点here。你可以在它的地方使用Ember.Select。

我不确定你的例子出了什么问题,但你有控制器操纵视图,这是不好的形式。观察控制器内容并在更改时更新。