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

时间:2014-11-16 14:58:52

标签: javascript angularjs angularjs-directive

我最近进入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: '='
        }
    };
}]);

3 个答案:

答案 0 :(得分:7)

只需将country[0]country[1]替换为country.codecountry.name

http://plnkr.co/edit/OIGGitze5LLehDes2MQ8?p=preview 或者我错过了什么?

答案 1 :(得分:3)

我认为您不需要为此制定新指令。已有一个内置的针对角度的选择指令,因此您为自己做了比必要更多的工作。所以可以做的是将该服务注入到页面的控制器中,然后将服务绑定到控制器的范围,就像您对指令所做的那样。它最终会看起来像:

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. *版本的最佳做法。阅读Todd Motto所说的一切。

答案 2 :(得分:2)

为可以重复使用的事物创建指令是个好主意,比如国家选择器。您希望将countries注入指令,然后可以使用ng-options对其进行迭代。 Plunker: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;
  }
}]);
相关问题