javascriptangularjsui-select2

UI-Select2 binding to object instead of property of object


I am using ui-select2, version 3.5.2, trying to do a single select, type-ahead and retrieve from REST api, drop down list. It looks like it is working except for one major issue, which is that, the ng-model's property gets set to an object {Id: "some id", text: "some text"} instead of the actual Id property. I cannot figure out how to tell ui-select2 control to set the ng-model property to the "Id" field of the object, instead of the whole object. I have tried various hacks with watchers but didnt get anywhere. I am sure there is something that I am missing because this is something that should be possible easily.

Here is my javascript code:

$scope.selectOptions = {
                placeholder: '- Select Value -',
                allowClear: true,                
                minimumInputLength: 2,
                initSelection: function (element, callback)
                {
                    if ($scope.myobj && $scope.myobj.Id && $scope.myobj.Id !== '00000000-0000-0000-0000-000000000000')
                    {   
                        $.ajax("../../api/objs/" + $scope.myobj.Id).done(function (data) {
                            var res = $(data).map(function (i, o) {
                                return {
                                    id: o.Value,
                                    text: o.Display
                                };
                            }).get();                            
                            callback(res[0]);                                                        
                        });
                    }
                },
                ajax:
                {
                    type: "GET",
                    url: function (term) {
                        return ["../../api", "objs", encodeURIComponent(term)].join("/");
                    },
                    dataType: "json",
                    contentType: "application/json",
                    cache: false,                    
                    results: function (data, page) {
                        return {
                            results: $(data).map(function (i, o) {
                                angular.extend(o, {
                                    id: o.Value,
                                    text: o.Display
                                });
                                return o;
                            }).get()
                        };
                    }
                }
            }

Here is my html code:

<div ui-select2='selectOptions' ng-model="myobj.Id" style="width:215px" />

Solution

  • I got around this by binding to a separate property and then adding a ng-change on my div and syncing the binding property's id field to actual property on my object.