具有动态默认值的 ng 选项
ng-options with dynamic default value
我在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>
单击此处查看演示。
相关文章:
- 如何使用AngularJs禁用ng选项中的选项
- 如何将ng选项的索引作为angularJs中的值传递给模型
- AngularJS ng选项在选择一个选项后删除了默认的空白值
- 当使用select作为标签时,如何使用ng选项禁用angularjs中的选项
- 从服务器获取数据并在选择控件中使用ng选项无法显示选项
- ng选项-用vm替换$scope
- Angularjs-设置不带ng选项的select的默认值
- ng选项-传递键而不是值
- Angular:如何使用ng选项进行四个单独的选择
- 使用ng选项,我如何筛选准确解释给定值的内容
- 角度Ng选项错误
- Angular.js通过对象关键点上的ng选项进行跟踪
- 为什么ng选项指令需要ng模型
- Angular js-ng选项不起作用
- 在<选择>使用angular ng选项可能使用ng init
- 如何在 AngularJS 的 ng 选项中设置值属性
- $localStorage array select with ng选项工作不正常
- 筛选ng选项时语法不正确
- Angularjs使用ng选项进行选择
- Angular中独特的ng选项