使用ng-model,ng-init,ng-options和表单集合选择角度设置

时间:2016-04-15 13:08:12

标签: angularjs ng-options ng-init

我正在尝试从JSON调用动态地在select元素上设置所选选项。如果使用此方法选项是静态的,我可以设置它,但对于我的生活,我无法在使用ng-options或ng-repeat填充选项时进行设置。这是我的一个下拉列表的HTML:

<select class="form-control" id="authQLang" name="authQLang" ng-model="content.languages" ng-options="item as item.name for item in languages track by item.code"  ng-init="content.languages == defaultLang" required>
    <option value="">Select a language</option>

    </select>

我控制器中的代码:

$scope.content = data.data;
    $scope.defaultAcct = data.data.defaultAccount.ID;
    $scope.defaultLang = data.data.defaultLanguage.code;
    $scope.accounts = [];
      angular.forEach(data.data.accounts, function(value, key) {
          $scope.accounts.push(value);
      });
    $scope.languages = [];
      angular.forEach(data.data.languages, function(value, key) {
          $scope.languages.push(value);
      });

JSON格式:

{
"code": 0,
"message": "",
"data": {
    "defaultAccount": {
        "ID": "6481618",
        "name": "Account X"
    },
    "defaultLanguage": {
        "code": "en-US",
        "name": "English US"
    },
    "accounts": [{
        "ID": "6481004",
        "name": " Account A."
    },...
    "languages": [{
        "code": "en-us",
        "name': "English US"
    },...

1 个答案:

答案 0 :(得分:1)

摆脱ng-init,你在控制器中设置这个值要好得多。从控制器更改它也会改变选择。

<select class="form-control" id="authQLang"
  name="authQLang" ng-model="content.languages"
  ng-options="item as item.name for item in languages track by item.code"
  required>
    <option value="">Select a language</option>
</select>

然后在你的控制器中:

$scope.content = data.data;
$scope.defaultAcct = data.data.defaultAccount.ID;
$scope.defaultLang = data.data.defaultLanguage.code;
$scope.accounts = [];
  angular.forEach(data.data.accounts, function(value, key) {
      $scope.accounts.push(value);
  });
$scope.languages = [];
  angular.forEach(data.data.languages, function(value, key) {
      $scope.languages.push(value);
  });

# add this:
$scope.content.languages = $scope.defaultLang

只需在您想要更改选择时更新$scope.content.languages

哦,你的==中有ng-init,这会阻止初始值设置正确。