使用ng-options进行选择输入

时间:2016-02-06 17:05:03

标签: angularjs select ng-options materialize

我正在使用ng-options进行选择输入。但它只是没有填充下拉列表。我使用materialize css作为css框架。

这是我的代码

<div class="col s6" >
    <select ng-options="bucket.id as bucket.name for bucket in buckets track by bucket.id" ng-model="new_transaction.bucket"></select>
</div>

Js Code

$scope.new_transaction = {
    "bucket":""
}

$scope.buckets = [
    {
        id:1,
        name:"bucket-1"
    },
    {
        id:2,
        name:"bucket-2"
    }
]

$(document).ready(function() {
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('select').material_select();
});

注意:控制台中没有错误。 下拉元素上的inspect元素显示了我

<div class="select-wrapper">
   <span class="caret">▼</span>
    <input type="text" class="select-dropdown" readonly="true" data-activates="select-options-b1cded87-bee7-c9cd-5564-c613f7439e7a" value="">
    <ul id="select-options-b1cded87-bee7-c9cd-5564-c613f7439e7a" class="dropdown-content select-dropdown" style="width: 294px; position: absolute; top: 0px; left: 0px; opacity: 1; display: none;">
    </ul>
    <select ng-options="bucket.id as bucket.name for bucket in buckets track by bucket.id" ng-model="new_transaction.bucket_id" class="initialized ng-pristine ng-untouched ng-valid"><option value="?" selected="selected"></option>
 <option label="Bucket-1" value="1">Bucket-1</option>
 <option label="Bucket-2" value="2">Bucket-2</option></select>

3 个答案:

答案 0 :(得分:0)

你可以申请

$('select').material_select();

仅在您准备好ngOptions指令完成时。 最简单和最常用的解决方案是将插件init放在$ timeout内:

$timeout(function(){
   $('select').material_select();
})

答案 1 :(得分:0)

您已经包含了角度,但是您还没有正确设置它以实际使用它。您需要为您要完成的任务创建模块,控制器和指令。

angular.module('app', []);

angular.module('app').controller('AppController', ['$scope', function($scope) {
   $scope.new_transaction = {
    bucket:""
   };

   $scope.buckets = [
   {
      id:1,
      name:"bucket-1"
   },
   {
      id:2,
      name:"bucket-2"
   }];


}]);

angular.module('app').directive('materialSelect', function() {
   return {
      restrict: 'A',
      link: function(scope, elem) {
         $(elem).material_select();
      }
   };
});

在您的身体标签上,包括:

<body ng-app="app">

在主要内容的容器上,包括:

<div ng-controller="AppController">
   <!-- your other content including the select -->
</div>

然后使用materialSelect指令作为这样的属性:

<select material-select ng-options="bucket.id as bucket.name for bucket in buckets track by bucket.id" ng-model="new_transaction.bucket"></select>

答案 2 :(得分:0)

如果之前有初始化存储桶,则异步请求ng-options将使其为空,因为ng-options在第一次修改时会占用存储桶。例如:

$scope.buckets = [];

$http.get('/get buckets/').then(function (result) {
  $scope.buckets = result.data;
});

因此,删除$scope.buckets = [];会使ng-options等到桶回调之后才会出现问题。