【问题标题】:Angularjs and UI-Select: how to select an option from codeAngularjs 和 UI-Select:如何从代码中选择一个选项
【发布时间】:2015-07-07 16:31:57
【问题描述】:

在 angularjs 中我有一个 ui-select:

<ui-select ng-model="itemSelected.selected" theme="selectize" ng-disabled="disabled">
   <ui-select-match placeholder="Select an item...">{{$select.selected.Name}}</ui-select-match>
   <ui-select-choices repeat="item in itemsList">
      <span ng-bind-html="item.Name"></span>
   </ui-select-choices>
</ui-select>

加载页面时如何从代码中选择一个项目? 当我在控制器中加载页面时,我得到$scope.itemsList:如何从controller 中选择特定项目?

谢谢

【问题讨论】:

  • 我不明白,你能更具体一点吗? $scope.itemsList 是数组还是对象?当你加载你的控制器时,你想将它与 ng-model 绑定吗?
  • 你能在你的 itemList 中提供一个示例项目吗?

标签: angularjs angular-ui ui-select2 ui-select


【解决方案1】:

您可以在控制器加载时自行设置

标记

<body ng-controller="DemoCtrl">
  <p>Selected: {{item.selected}}</p>
  <ui-select ng-model="item.selected" theme="select2" ng-disabled="disabled" style="min-width: 300px;">
    <ui-select-match placeholder="Select a item in the list">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="item in items | propsFilter: {name: $select.search, age: $select.search}">
      <div ng-bind-html="item.Code | highlight: $select.search"></div>
    </ui-select-choices>
  </ui-select>
</body>

代码

app.controller('DemoCtrl', function($scope, $http) {
  $scope.disabled = undefined;

  $scope.clear = function() {
    $scope.item.selected = undefined;
  };

  $scope.item = {};
  $scope.items = [
    { name: 'Item1', Code: 'Code1', },
    { name: 'Item2', Code: 'Code3'},
    { name: 'Item3',  Code: 'Code4'},
    { name: 'Item4',  Code: 'Code4' },
    { name: 'Item5', Code: 'Code5' },
  ];

  $scope.item.selected = $scope.items[0] //here you can set the item selected
});

Working Plunkr

【讨论】:

    【解决方案2】:

    @Pankaj Parkar 的 plunkr 不再适用于预期用途,所以我将它分叉并让它在这里工作:

    http://plnkr.co/edit/Y6cdgJQ3YPq7Ncb3bT4A?p=preview

    涉及在控制器中实际设置所选项目的关键更改:

    $scope.address = {};
    $scope.refreshAddresses = function(address) {
        var params = {address: address, sensor: false};
        return $http.get(
        'http://maps.googleapis.com/maps/api/geocode/json',
        {params: params}
        ).then(function(response) {
        $scope.addresses = response.data.results
        $scope.address.selected = $scope.addresses[0];
        $scope.$apply();
        });
    };
    $scope.refreshAddresses('New York, NY');
    

    添加的关键是 $scope.address.selected = $scope.addresses[0];$scope.refreshAddresses('New York, NY'); 以使其运行。

    我还更新了其他选择以进行预填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多