通过 Angular 指令在 html 模板中迭代配置数组

Iterate config array in html template via Angular directives?

本文关键字:迭代 配置 数组 Angular 指令 html 通过      更新时间:2023-09-26

我最近进入了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.codecountry.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;
  }
}]);