Angularjs 在我的angular应用程序中使用ngChange=“myFunction()”时,无法在select>选项上设置默认值

Angularjs 在我的angular应用程序中使用ngChange=“myFunction()”时,无法在select>选项上设置默认值,angularjs,angular-ngmodel,ng-options,angularjs-ng-change,angularjs-select,Angularjs,Angular Ngmodel,Ng Options,Angularjs Ng Change,Angularjs Select,我正在构建一个有角度的应用程序;我必须设置一个来自控制器$scope.ecole.niveauid的默认值。 为此,我只编写了以下代码: <select class="form-control" name="niveau"> <option value="{[{niveau.id}]}" ng-repeat="niveau in niveaux" ng-selected="niveau.id == ecole.

我正在构建一个有角度的应用程序;我必须设置一个来自控制器$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>
一切正常,但我不再有默认值。
请说明如何根据$scope controller设置默认值并检索更改后的值?

在控制器的作用域上创建选定的值对象,并在设置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,因为它将自动使用选项值value={[{niveau.id}]}绑定ng模型。加载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>

在重新加载功能中有什么?选择了ng中的ecole.niveauid是什么?是的,谢谢,它工作得很好。但是我将$scope.selectedValue={id:2}更改为$scope.selectedValue={id:$scope.ecole.niveauid.toString},因为我希望该值基于一个范围。是的,太完美了!我不知道$scope.ecole.niveauid.toString的确切路径,所以我用注释对其进行了硬编码,很高兴它成功了!:
$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
}
<select class="form-control"
          ng-model="selectedValue.id"
          ng-change="reload()">

          <option value="{[{niveau.id}]}"
                  ng-repeat="niveau in niveaux">
                  {[{niveau.libelle}]}</option>
</select>