通过 Angular 指令在 html 模板中迭代配置数组
Iterate config array in html template via Angular directives?
我最近进入了AngularJS,并试图创建一个注册表单,我将从其他地方广泛使用的JavaScript配置中填写国家/地区列表,因此我将其保留为JS对象。
我一直在尝试在我的选择输入上使用 ng-repeat-start 和 *-end,但它失败了。
主要问题是,如何加载国家/地区数组并在模板中迭代它?
编辑: 30.11.2014 - 更好的例子
.HTML:
<div class="form-group">
<label for="phone">Country</label>
<select-country ng-model="credentials.country"></select-country>
<pre>{{credentials.country}}</pre>
</div>
文件:
/public/directives/countrySelector.directive.js
指令内容:
'use strict';
angular.module('app', [])
.value('countries', [
{name: 'Afghanistan', code: 'AF'},
{name: 'Åland Islands', code: 'AX'}
])
.directive('selectCountry', ['countries', function (countries) {
function link (scope, element, attrs) {
scope.countries = countries;
}
return {
template: '<select ng-options="country[1] as country[0] for country in countries"' +
' ng-model="credentials.country">' +
'</select>',
link: link,
scope: {
credentialsCountry: '='
}
};
}]);
只需将country[0]
和country[1]
替换为country.code
和country.name
http://plnkr.co/edit/OIGGitze5LLehDes2MQ8?p=preview还是我错过了什么?
我认为您不需要为此制定新指令。 已经有一个内置的 select 指令用于角度,因此您为自己所做的工作比必要的要多。因此,您可以做的是将该服务注入页面的控制器中,然后将服务绑定到控制器的作用域,就像您对指令所做的那样。 它最终看起来像这样:
angular.module('app', [])
.value('countries', [
{name: 'Afghanistan', code: 'AF'},
{name: 'Åland Islands', code: 'AX'}
]);
并且您有一个控制器
app.controller('whateverTheControllerIs', ['countries', '$scope', function (countries, $scope) {
$scope.countries = countries;
});
然后您的范围可用于模板
<div class="form-group">
<label for="phone">Country</label>
<select ng-options="country.name for country in countries" ng-model="credentials.country"></select>
<pre>{{credentials.country}}</pre>
</div>
作为旁注:如果您想了解最新 Angular 1.* 版本的最佳实践。 阅读托德·莫托所说的一切。
最好
为可以经常重用的东西(如国家/地区选择器)创建指令。您希望将countries
注入到指令中,然后可以使用 ng-options
对其进行迭代。普伦克:http://plnkr.co/edit/zfkeLNQ0LHxR7FB0nM18?p=preview
.directive('selectCountry', ['countries', function (countries) {
var directive = {
template: '<select ng-options="country[1] as country[0] for country in countries"' +
' ng-model="ngModel">' +
'</select>',
link: link,
scope: {
ngModel: '='
}
};
return directive;
function link (scope, element, attrs) {
scope.countries = countries;
}
}]);
相关文章:
- 如何在javascript中迭代数字列表
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 如何迭代Array.prototype函数
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 在ejs-partial中对JSON对象进行迭代
- 如何在DataTables 2.1中迭代对象数组
- 使用递归属性迭代保留属性结构
- 正在停止.在jquery中的特定时间间隔内,每次迭代的每次执行
- 如果30秒未单击,请应用CSS一次,将其删除,然后重新迭代
- 主干-从模板中迭代的集合中获取特定的模型
- 创建一个方法,通过一个窗口进行迭代并获取Titanium中的所有控件
- 什么's是在javascript中迭代项的最佳方式
- 为什么这只是迭代 HTMLCollection 的奇怪元素
- 是否“;对于的“;循环迭代遵循JavaScript中的数组顺序
- Babel编译错误:找不到模块核心js/library/fn/get迭代器
- 在es6中,将带有回调的事件侦听器设置为可迭代的
- jQuery-迭代不正确?(太长,无法执行)
- 每个$.,循环获胜't逐个迭代HTML元素
- 通过 Angular 指令在 html 模板中迭代配置数组
- 如何迭代Google Analytics配置文件ID's