Select2不知道所选值的相应文本

时间:2015-05-12 01:02:03

标签: javascript angularjs jquery-select2

我使用远程数据源作为选项。当我从服务器加载表单数据时,它只包含select元素的值。在这种情况下,select2不知道要向用户显示的相应文本。这种常见情况是否有内置的可重用机制?

如何使用ajax获取数据时设置当前选择的值/文本?

$('select#test').select2({
                    ajax: {
                        url: "user/combo",
                        dataType: 'json',
                        delay: 250,
                        cache: true
                    }
                });
            }
        }

实际上,我正在尝试创建一个角度指令,如下所示:

app.directive('mehrUserCombo', ['$http', function ($http) {
        return {
            link: function (scope, element, attr) {
                element.select2({
                    ajax: {
                        url: "user/combo",
                        dataType: 'json',
                        delay: 250,
                        cache: true
                    }
                });
            }
        }

3 个答案:

答案 0 :(得分:6)

这些是你的ajax选项:

ajax: {
  // The number of milliseconds to wait for the user to stop typing before
  // issuing the ajax request.
  delay: 250,
  // You can craft a custom url based on the parameters that are passed into the
  // request. This is useful if you are using a framework which has
  // JavaScript-based functions for generating the urls to make requests to.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @returns The url that the request should be made to.
  url: function(params) {
    return UrlGenerator.Random();
  },
  // You can pass custom data into the request based on the parameters used to
  // make the request. For `GET` requests, the default method, these are the
  // query parameters that are appended to the url. For `POST` requests, this
  // is the form data that will be passed into the request. For other requests,
  // the data returned from here should be customized based on what jQuery and
  // your server are expecting.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @returns Data to be directly passed into the request.
  data: function(params) {
    var queryParameters = {
      q: params.term
    }

    return queryParameters;
  },
  // You can modify the results that are returned from the server, allowing you
  // to make last-minute changes to the data, or find the correct part of the
  // response to pass to Select2. Keep in mind that results should be passed as
  // an array of objects.
  //
  // @param data The data as it is returned directly by jQuery.
  // @returns An object containing the results data as well as any required
  //   metadata that is used by plugins. The object should contain an array of
  //   data objects as the `results` key.
  processResults: function(data) {
    return {
      results: data
    };
  },
  // You can use a custom AJAX transport function if you do not want to use the
  // default one provided by jQuery.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @param success A callback function that takes `data`, the results from the
  //   request.
  // @param failure A callback function that indicates that the request could
  //   not be completed.
  // @returns An object that has an `abort` function that can be called to abort
  //   the request if needed.
  transport: function(params, success, failure) {
    var $request = $.ajax(params);

    $request.then(success);
    $request.fail(failure);

    return $request;
  }
}

关于processResult函数的

使用:

 processResults: function(data) {
   $('select#test').select2("val", YOUR VALUE FROM PROCESSED DATA); //set the value
   return {
     results: data
   };
 }

答案 1 :(得分:1)

您可以使用数据&结果函数在ajax调用中根据您的数据请求,解析和设置json数据。

这是我的一些生产代码中的一个小代码片段,它与您提出的问题类似:

$(".autocomplete-search").select2({
  placeholder: "Pizza, Movies, etc...",
  minimumInputLength: 2,
  ajax: {
    url: '/find-suggestions.json',
    dataType: 'json',
    quietMillis: 250,
    data: function(params, page) {
      return {
        query: params,
        page: page
      };
    },
    results: function(data, page) {
      var more, search_all, searched_for;
      searched_for = $(".select2-search input").val();
      search_all = [
        {
          query: searched_for
        }
      ];
      more = data.suggestions.stores.length >= 1;
      return {
        results: search_all.concat(data.suggestions.categories, data.suggestions.stores),
        more: more
      };
    }
  }
});

data:我使用params值将原始值传递给我的ajax api,然后在results:中返回数据;我可以获得原始输入值(searched_for)并将其与下面的其他数据配对,解析出来并将其连接起来,如示例中所示。

我不知道如何在没有更多细节的情况下为您提供您正在寻找的确切答案,但我相信代码段会说明您要完成的行为类型。另外,我刚刚注意到@ prollyGeek的回答是在我输入时得到的,请在评论中阅读文档,非常有帮助。

答案 2 :(得分:1)

你可以检查这个角度模块以适当的方式将select2包装成角度:ui-select因为它使用角度绑定。您应该能够在承诺解决后设置值返回。  无论如何,你不应该使用ajax()函数,而是使用$ http代替所有异步调用。

这是一个例子:

<ui-select ng-model="person.selected" theme="select2" ng-disabled="disabled" style="min-width: 300px;">
    <ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">
      <div ng-bind-html="person.name | highlight: $select.search"></div>
      <small>
        email: {{person.email}}
        age: <span ng-bind-html="''+person.age | highlight: $select.search"></span>
      </small>
    </ui-select-choices>
  </ui-select>

示例中的绑定值是&#34; person.selected&#34;列表是&#34;人员&#34; 你只需要在你的控制器中做这样的事情:

$http.get("/yourdatauri").success(function(data){
  $scope.people = data;
});

希望它会帮助你。