Angularjs and UI-Select: how to select an option from code

与世无争的帅哥 提交于 2019-12-05 09:42:11

You can set that on controller load itself

Markup

<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>

Code

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

The plunkr by @Pankaj Parkar was no longer working for the intended usage so I forked it and got it working here:

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

The key changes involved actually setting the selected item in the controller:

$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');

The key addition is $scope.address.selected = $scope.addresses[0]; and $scope.refreshAddresses('New York, NY'); to get it to go.

I also updated the other selects to prepopulate, as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!