1

与 ember 一起使用时,我很难在 select2 组件上显示所选选项。这是我的控制器的样子:

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");
}});

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

更新: 在此处输入图像描述 这就是我所说的,选择了该选项,但文本没有出现在选择的顶部,即使在我使用“buuda”建议的选择视图之后,仍然是同样的问题!

4

1 回答 1

2

I wrote a select2 view that extends Ember.Select. You can find the gist here. You can use in it place of Ember.Select.

I am not sure what is going wrong with your example, but you are having the controller manipulate the view, which is not good form. Have the view observe the controller content and update upon change.

于 2013-08-26T15:11:06.737 回答