我正在构建一个有角度的应用程序;并且我必须设置来自$scope.ecole.niveauid
控制器的默认值。为此,我只写了以下代码:
<select class="form-control" name="niveau">
<option value="{[{niveau.id}]}"
ng-repeat="niveau in niveaux"
ng-selected="niveau.id == ecole.niveauid">
{[{niveau.libelle}]}
</option>
</select>
它确实很棒。
现在,我需要检索选定的值,并将其传递给控制器的功能。所以我补充说:
<select class="form-control"
ng-model="niveau"
ng-change="reload(niveau)">
<option value="{[{niveau.id}]}"
ng-repeat="niveau in niveaux"
ng-selected="niveau.id == ecole.niveauid">
{[{niveau.libelle}]}</option>
</select>
在我的控制器中,我已经:
$scope.reload = function (item) {
console.log(item);
}
$scope.niveaux = [
{
"id": 1,
"libelle": "level1"
},
{
"id": 2,
"libelle": "level2"
},
{
"id": 3,
"libelle": "level3"
}];
$scope.ecole.niveauid = 3;
一切正常,但是我没有默认值了。请如何设置默认值并基于$ scope控制器检索更改的值?
在设置niveaux之后,在控制器的作用域上创建一个选定的值对象,并在此对象上设置id属性。
$scope.niveaux = [
{
"id": 1,
"libelle": "level1"
},
{
"id": 2,
"libelle": "level2"
},
{
"id": 3,
"libelle": "level3"
}];
$scope.selectedValue = {id: "2"}; //selected value onload (pass your selected value here)
$scope.reload = function (){
var selectedId = $scope.selectedValue.id;
//do something
}
然后,在HTML中,您只需要更新绑定即可。您不再需要指定ng-selected,因为它将自动将ng-model与option value绑定value="{[{niveau.id}]}"
。加载niveaux列表后,只需设置一次选定的属性。
<select class="form-control"
ng-model="selectedValue.id"
ng-change="reload()">
<option value="{[{niveau.id}]}"
ng-repeat="niveau in niveaux">
{[{niveau.libelle}]}</option>
</select>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句