在select元素中调用函数来填充ngOptions源?

时间:2016-05-23 12:02:19

标签: javascript angularjs drop-down-menu ng-options

我有<select>如下:

<div ng-show="myCtrl.name == 'Jack'">
        <select ng-model="myCtrl.selectedValue" ng-options="value.id as value.title for value in myCtrl.valueDrpValues">
            <option value=""> Select One ...</option>
        </select>
</div>

myController.js中,我有一个应该填充myCtrl.valueDrpValues的函数。如何从select标签中调用此函数?我测试了ng-init,但它没有用。另外,我完全从ng-option调用了该函数,但它也没有用。 (如下:)

ng-options="value.id as value.title for value in definitionCtrl.fillValueDrp()"

2 个答案:

答案 0 :(得分:0)

您可以使用ng-init

在那里调用你的函数,你的数组就会被填充,例如:

<div ng-init="fillValueDrp()">
    <div ng-show="myCtrl.name == 'Jack'">
        <select ng-model="myCtrl.selectedValue" ng-options="value.id as value.title for value in myCtrl.valueDrpValues">
            <option value=""> Select One ...</option>
        </select>
    </div>
</div>

答案 1 :(得分:0)

试试这个。

var app = angular
  .module('MyApp', [
  ])
.controller('Main', ['$scope', function ($scope) { 
  var self = this;
  self.items = [];
  self.name = "Jack";
   
  self.fillValueDrp = function(){
     for(var i=0 ;i < 5; i++){
         self.items.push({"id":i,"title":i});
        }
    }

}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl">
      <div ng-show="myCtrl.name == 'Jack'" ng-init= "myCtrl.fillValueDrp()">
        <select ng-model="myCtrl.selectedValue "ng-options="value.id as value.title for value in myCtrl.items">
            <option value=""> Select One ...</option>
        </select>
</div>
    </div>