Search code examples
javascriptjqueryangularjsui-select2angularjs-select2

Are there any applicable options to Angular ui-select2 directive?


Given the following Angular selec2 controller:

                <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject">
                    @*ng-options="project.WebsiteName for project in projectList"*@
                    <option value=''></option>
                    <option ng-repeat="project in projectList" ng-value="'{{ project.WebsiteGUID }}'">{{project.WebsiteName}}</option>
                </select>

Model data is retrieved as follows from the controller:

    $scope.projectList = dataFactory.getList("")   // no parameters
                            .success(function (result) {
                                $scope.projectList = result.value;
                                $("#projectListSelection").select2({ width: '240' });
                            })
                            .error(function (error) {
                                customUIFunctions.showError("Data Error - Unable to Load Project List"); // use default error message
                                console.log("data error");
                            });

Here's the issue:

  1. When the control first appears on the screen, it looks like a plain old select drop-down control
  2. For a fraction of a second, then its width goes to 0
  3. The control's UI is updated again to look like the select2 control, however its width is only as small as the placeholder
  4. After the control is loaded with data, it then resizes to 240px

When I try setting the width before the data is retrieved (before $scope.projectList = ...) I get the following errors:

query function not defined for Select2 s2id_projectListSelection ... angular.js:9402 RangeError: Maximum call stack size exceeded ...

Which makes sense as the DOM isn't fully loaded. So...

     $(document).ready(function () {
        $("#projectListSelection").select2({ width: '240' });
    });

However I still see the same issue, where the width conforms first to the placeholder, then to the wider setting once data is loaded.

I managed to get around this doing:

<select ui-select2 id="projectListSelection" style="width:240px;" . . .

However, that's kind of ugly.

The questions:

  1. Is there a width option that will hold true whether or not data is loaded?
  2. Is there a placeholder option that will allow me to display a message such as "Loading Data..." then display a different message ie. "Select a project ..." once the data is loaded?

Solution

    1. Your best option here is probably custom CSS that overrides the default.
    2. Create a variable in your controller scope called placeholder with the initial value of "Loading data..." then watch for your data to load and change scope.placholder to "Select a Project...". Then on your element use placeholder="{{ placeholder }}"