2

I've been looking everywhere for a solution to this but can't find it.

I have a element in my DOM that I'm populating with results obtained from DB (server side). This is a multi-select select, by the way, so it can contains several values.

What I'm trying to do is:

  • If only a single value is returned, then assign that value to the field, otherwise (0 or more) leave empty.

That said, this is what I've tried:

View (this includes some Jinja2 stuff that you simply ignore):

 <div class="control-group">
        <label class="control-label" for="channels">Channels <span style="font: 15px bold; color:red">*</span></label>
        <div class="controls">
            <select id="channels"
                    ui-select2="configPartSelect2"
                    multiple="multiple"
                    ng-disabled="matchable.perm == 'r'"
                    ng-change="channelsChanged()"
                    ng-model="matchable.channels"
                    style="width: 350px"
                    value=""
                    required>
                {% raw %}
                <option value="{{ o.id }}" ng-repeat="o in selectOptions.channels | filter:restrictPlatform">{{ o.title }}</option>
                {% endraw %}
            </select>
        </div>
    </div>

Note the value="", I'll get back to this with the controller:

 $scope.configPartSelect2 = { 
        initSelection : function (element, callback) {
            console.log("Yep!");
            callback($(element).data('$ngModelController').$modelValue);
        }};

Using the initSelection was a recommendation found here and here. This does not work, after some digging...I've found that this is only called if you have set a value...and that's why I tried setting select value=""...although this looks dull to me.

So the problem is that initSelection is never called, thus I can't set any value. I'm not particularly eager to use this approach, any other would suffice...I've seen this, but it looks like some jQuery hack.

Any ideas/suggestion? I can't provide a meaningful Plancker or JSFiddle because the code just a part of a much bigger app and it won't make much sense to do so.

Thanks!

EDIT: I've added a watch for the select, but I don't how to update the view from the controller:

    $scope.$watch('matchable.channels', function(newVal,oldVal){
        //If number of channels is 1, load it by default in channel selector
        if ($scope.selectOptions.channels.length == 1){
            $scope.matchable.channels[0] = $scope.selectOptions.channels[0];
        }
        console.log(newVal,oldVal);
    });

EDIT++: Fixed it by passing the channel id, if anyone else is having this issue, make sure you're providing the id to whatever you're using in your ui-select2 field, like so:

$scope.matchable = {channels : [$scope.fullChannelList[0].id]};
Community
  • 1
  • 1
AlejandroVK
  • 7,373
  • 13
  • 54
  • 77

0 Answers0