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

Can't set a default value on select>option when using ngChange="myFunction()" in my angular app

我正在构建一个 angular 应用;并且我必须设置来自控制器 $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 与选项值 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>