具有动态默认值的 ng 选项

ng-options with dynamic default value

本文关键字:ng 选项 默认值 动态      更新时间:2023-09-26

我在javascript中有这个结构

$scope.prefixes = [
  {'id': 'Mr', 'name': 'Mr.'},
  {'id': 'Mrs', 'name': 'Mrs.'}                
];

我得到我的用户是否是这样的先生或夫人

JSON.parse(localStorageService.get("user")).prefix. 

根据用户登录时获得的数据。因此,用户的前缀始终是动态的。

这是我的想法,即获取用户是先生还是夫人,将其放在范围变量中,然后在 HTML 中使用该范围变量为选择标记设置

默认值
 $scope.prefixes = [
   {'id': 'Mr', 'name': 'Mr.'},
   {'id': 'Mrs', 'name': 'Mrs.'}                
 ];

  $scope.readPrefixesInit;
  for (i = 0; i < $scope.prefixes.length; i++) { 
     //if dynamic is equal with one of the ids, get the name
     if ($scope.prefixes[i].id == JSON.parse(localStorageService.get("user")).prefix){
        $scope.readPrefixesInit = $scope.prefixes[i].name;                                                          
      }
 }   

然后在 HTML 中

  <select required autofocus class="form-control"     
        ng-model="prefix" 
        ng-init="prefix =  {{ readPrefixesInit }}"
        ng-options="f.id as f.name for f in prefixes">          
        <option value="">Select Prefix</option>  
  </select> 

这是行不通的。

我收到此错误Syntax Error: Token '{' invalid key at column 12 of the expression [prefix = {{ readPrefixesInit }}] starting at [{ readPrefixesInit }}].

我得到了我的下拉菜单,但没有预先选择任何值。

我该如何解决这个问题?谢谢

您的 HTML 部件中存在语法错误。该行:

ng-init="prefix =  {{ readPrefixesInit }}"

应该是:

ng-init="prefix = readPrefixesInit"

实际上,您不需要中间readPrefixesInit变量,可以改用prefix

.JS:

$scope.prefixes = [
  {'id': 'Mr', 'name': 'Mr.'},
  {'id': 'Mrs', 'name': 'Mrs.'}                
];
$scope.prefix = null;
for (i = 0; i < $scope.prefixes.length; i++) { 
    //if dynamic is equal with one of the ids, get the name
    if ($scope.prefixes[i].id == JSON.parse(localStorageService.get("user")).prefix) {
        $scope.prefix = $scope.prefixes[i].name;                                                          
    }
}

模板:

<select required autofocus class="form-control"     
      ng-model="prefix" 
      ng-options="f.id as f.name for f in prefixes">          
    <option value="">Select Prefix</option>  
</select> 

单击此处查看演示。