Angular ui-select默认选择的值

时间:2016-10-08 19:16:16

标签: angularjs ui-select

我在Angular中使用ui-select在我的页面中有一个选择框。我可以通过键入进行搜索,当我选择值时,将显示名称[哪个很好],并且ng-model具有所选的值id [也是正确的]

现在我尝试加载已保存记录的视图。我希望选中的框能够预先填充。

但事实并非如此!

这是我的HTML

<ui-select ng-model="vm.product.category">
    <ui-select-match placeholder="Type to search">{{ (vm.categories | filter : { id : vm.product.category } : true)[0].name }}</ui-select-match>
    <ui-select-choices repeat="category.id as category in (vm.categories | filter: {name: $select.search})">
        <span ng-bind-html="category.name | highlight: $select.search"></span>
    </ui-select-choices>
</ui-select>

这是我的控制器,

app.controller('productDetailsController', [
    '$scope', 'Product',
    function ($scope, Product) {
        var vm = this;
        vm.product = {};
        vm.categories = [{name: "General", id: "1"}, {name: "Product", id: "2"}]

        Product.get({id: id}).$promise.then(function (data) {
            vm.product = data.data;
        }, function (error) {
            alert(error);
        });
    }
]);

当我从数据库加载记录时,我的model()有ID。但我希望将名称显示给用户。

我该怎么做?我在这里做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var app = angular.module('app', ['ui.select']);
app.service('myservice', ['$timeout', '$q',
  function($timeout, $q) {
    this.getData = function() {
      var defer = $q.defer();
      //Here, $timeout corresponds to $http
      $timeout(function() {
        defer.resolve({
          'data': {
            product_name: "Galaxy S3",
            product_description: "Galaxy S3 desc",
            category: 1,
            is_active: true
          }
        });
      }, 1000);
      return defer.promise;
    }
  }
]);
app.controller('productDetailsController', ['$scope', 'myservice',
  function($scope, myservice) {
    var vm = this;
    vm.product = {};
    vm.categories = [{
      name: "General",
      id: "1"
    }, {
      name: "Product",
      id: "2"
    }];

    myservice.getData().then(function(data) {
      vm.product = data.data;
    });

  }
]);
&#13;
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-select/0.11.2/select.css" rel="stylesheet" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-select/0.11.2/select.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-sanitize.js"></script>

<div ng-app="app" ng-controller="productDetailsController as vm">
  <ui-select ng-model="vm.product.category">
    <ui-select-match placeholder="Type to search">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="category.id as category in vm.categories | filter: {name: $select.search}">
      <div ng-bind="category.name | highlight: $select.search"></div>
    </ui-select-choices>
  </ui-select>
</div>
&#13;
&#13;
&#13;