我正在研究angularjs应用程序。我希望角度控制器中的下拉列表中的选定值。请建议。下面是代码。
<select>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
js code:
myApp.controller('myController', function ($rootScope,$scope) {
//business logic
$rootScope.selectedValue='red';//I want the value of the dropdown selected, by default it is first option red
})
上面的控制器在页面加载时调用,如何将从下拉列表中选择的值分配给控制器的$ rootScope变量。
答案 0 :(得分:2)
<select ng-model="selectedValue">
并且,建议不要在rootscope
中使用原始道具。看到
updated fiddle如果可能的话,请避免使用rootcope。,只使用$ scope of controller。
答案 1 :(得分:0)
您应该将ng-model
添加到select
代码。
示例:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.showPopup=function(){
alert($scope.MyData);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" ng-model="MyData">
<option disabled selected value>-- select an option --</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<a class="btn btn-primary add-contract-button pull-right" ng-click="showPopup()">Click to show selected value</a>
</div>
答案 2 :(得分:0)
在您的代码中尝试此操作。
在HTML中,更改您的选择,如下所示
<select ng-model="colorSelected" ng-change="selectColor(colorSelected)">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
在JS或Controller中,按如下方式访问它,
myApp.controller('myController', function ($rootScope,$scope) {
$rootScope.selectedValue=$scope.colorSelected;
$scope.selectColor = function(colorSelected){
// use the colorSelected and set your alerts or basically handle anything
}
})
答案 3 :(得分:0)
在HTML中编写此代码:
<div ng-controller="myController">
<select ng-model="selectedValue">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
在JS中:
var myApp = angular.module('myApp',[]);
myApp.controller('myController', function ($rootScope,$scope) {
//business logic
$rootScope.selectedValue='red';//I want the value of the dropdown selected, by default it is first option red
})