如何从带有angularjs的下拉列表中获取值

时间:2016-11-29 10:19:45

标签: javascript html css angularjs

我使用后端的数据填充了一个选择框,但效果很好,但是当我点击一个项目来获取它的值时,它给了我未定义的内容:

dossiers

这是功能:

<div class="col-md-5">
  <label class="child-label" for="existing-phases">Existing:&nbsp;&nbsp;</label>
  <select class="form-control" ng-model="MyData">
    <option disabled selected value>-- select an option --</option>
    <option ng-repeat="var in payloadSecteur" value="{{var.id}}">{{ var.secteur }}
    </option>
  </select>
  <a class="btn btn-primary add-contract-button pull-right" ng-click="showPopup()">+</a>
</div>

4 个答案:

答案 0 :(得分:0)

您是否已将您的html代码放入div并使用ng-app和ng-controller定义并在Angular文件中定义它们?还要记住将Angular函数写入控制器。

HTML:

<div ng-app="myApp" ng-controller="myCtrl">

  <p>Select a car:</p>

  <select ng-model="selectedCar" ng-options="x for (x, y) in cars">
  </select>

  <h1>You selected: {{selectedCar}}</h1>

</div>

角:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.cars = {
        car01 : "Ford",
        car02 : "Fiat",
        car03 : "Volvo"
    }
});
</script>

另请注意,您不必使用<option>代码 - <select> ng-options即可。

答案 1 :(得分:0)

这是代码的工作片段,没有在option标签中设置的value属性,并且选项已经过硬编码,它运行正常

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <label class="child-label" for="existing-phases">Existing:&nbsp;&nbsp;</label>
  <select class="form-control" ng-model="MyData">
    <option disabled selected value>-- select an option --</option>
    <option>heldfd</option>
    <option>asdf</option>
    <option>asdf</option>
    <option>asdf</option>
  </select>
  <a class="btn btn-primary add-contract-button pull-right" ng-click="showPopup()">+</a>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.showPopup=function(){
  alert($scope.MyData);
};
});
</script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

<div ng-controller="MyCtrl">

    <div class="col-md-5">

        <label class="child-label" for="existing-phases">Existing:&nbsp;&nbsp;</label>

        <select class="form-control" ng-model="MyData" ng-options="payloadSecteur for payloadSecteur in payloadSecteur"></select>

        <a class="btn btn-primary add-contract-button pull-right" ng-click="showPopup()">+</a>

    </div>

</div>
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {


  $scope.payloadSecteur = ['one', 'two', 'three', 'four'];

  $scope.showPopup = function() {
    console.log('eee');
    console.log($scope.MyData);
  };

}

JSFiddle

答案 3 :(得分:-1)

试试这个: 将ng-model作为参数传递给showPopup(),如

ng-click="showPopup(MyData)"

在控制器中

$scope.showPopup=function(selectedData){
alert('eee');
alert(selectedData);
};