AngularJS动态创建选择框-ngModel未注册

AngularJS Dynamically Creating Select Box - ngModel Not Registering

本文关键字:-ngModel 注册 选择 动态 创建 AngularJS      更新时间:2023-09-26

我使用一个选择框来有条件地生成第二个选择框。选择框填充正确,并且在元素的Chrome检查器中一切看起来都很好。

问题是ng模型(在下面的代码示例中,ng模型="commandName")没有正确注册正确的选择值。因此,如果您在示例中查看,末尾的{{commandName}}输出正确地输出了第一个选择框,但没有输出第二个选择框。

这是个虫子吗?有人能推荐一种解决这个问题的替代方法吗?

除了commandName没有在底部的p标记中输出任何内容,但commandType输出之外,其他一切似乎都正常工作。

    <select ng-model="commandType" class="form-control" ng-init="commandType = ''; command = ''">
      <option value=""></option>
      <option ng-repeat="commandGroup in commandList" value="{{$index}}">{{commandGroup.name}}</option>
    </select>
    <!-- Shown if something is selected in the select box above -->
    <select ng-model="commandName" class="form-control" ng-if="commandType !== ''">
      <option value=""></option>
      <option ng-repeat="exactCommand in commandList[commandType].commands" value="{{$index}}">{{exactCommand.name}}</option>
    </select>
    <p>{{commandName}}</p>

AngularJS代码:

$scope.initCommandList = function () {
  $http({
    method: 'GET',
    url: $rootScope.webserver + 'admin/rterminalCommandList/',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  }).success(function (data) {
    console.log("Command list");
    console.log(data.data);
    $scope.commandList = data.data;
  });
};
$scope.initCommandList();

POST响应:

{
  "data"
:
  [{
    "id": 2,
    "name": "Application",
    "commands": [{
      "id": 3,
      "name": "Delete Smartcare data",
      "syntax": "su -c pm clear com.patasonic.android.smartcare",
      "comment": "Deletes Smartapp data"
    }]
  }, {
    "id": 1,
    "name": "Bluetooth",
    "commands": [{
      "id": 2,
      "name": "Bluetooth Controls. Turn off",
      "syntax": "bluetooth@ off",
      "comment": "Turns off device bluetooth"
    }, {"id": 1, "name": "Bluetooth Controls. Turn on", "syntax": "bluetooth@ on", "comment": "Turn on bluetooth"}]
  }], "header"
:
  {
    "messages"
  :
    [], "response_code"
  :
    200
  }
}

我建议您使用"select ng options"而不是"option ng repeat"https://docs.angularjs.org/api/ng/directive/ngOptions

<select ng-model="myModel"
ng-options="command as command.name for command in commandList">
</select>

下面是一个jsfiddle示例:

http://jsfiddle.net/jcamelis/5y086ytr/4/

我希望它能有所帮助。