【问题标题】:how to use one ng-repeat over a nested object to populate multiple labels and options in a form如何在嵌套对象上使用一个 ng-repeat 来填充表单中的多个标签和选项
【发布时间】:2014-01-09 19:24:07
【问题描述】:

解释:

我想使用 one ng-repeat 指令,该指令遍历名为 $scope.templates 的嵌套 JavaScript 对象来创建和填充表单的标签和字段。


当前代码使用多个 ng-repeats 和硬编码标签,以获得预期结果

JSbin Link

JS:

  angular.module('myApp', [])
        .controller('MainCtrl', function($scope) {

          $scope.templates = {
            pages: ['home', 'about'],
            posts: ['blog', 'lab']

          };

     });

我想使用pages:posts: 作为标签 和数组[] 作为<options> 到选择菜单

HTML:

  <div class="container" ng-controller="MainCtrl">
      <h3>Templates:<small>choose a template</small></h3>
    <form action="" class="col-lg-12" >

    <div>
          <label for="templates">Pages</label>
          <select class="form-control" >

            <option ng-repeat="template in templates.pages" value = "{{ template }}"> {{ template }}</option>
          </select>

    </div>
    <div>
          <label for="posts">Posts</label>

          <select class="form-control" >
            <option ng-repeat="template in templates.posts" value = "{{ template }}"> {{ template }}</option>
          </select> 

    </div>
    </form>

  </div>

这是JSbin

【问题讨论】:

  • 如果你打算让它保持干燥,那么你需要创建一个自定义指令。
  • 查看下面的解决方案

标签: javascript jquery html angularjs angularjs-ng-repeat


【解决方案1】:

HTML

<div ng-app='currentApp'>
    <div ng-controller='ACtrl'>
        <form-control templates='templates'></form-control>
    </div>
</div>

指令

var currentApp = angular.module('currentApp', []);
currentApp.directive('formControl', ['$compile', function ($compile) {

    return {
        restrict: 'EA',
        scope: {
            templates: '='
        },
        template: '<div ng-repeat="(key, prop) in templates">' +
        '<label for="templates">{{key}}</label>' +
                      '<select class="form-control">' +
                        '<option ng-repeat="template in templates[key]" value = "{{template}}">' +
                            '{{template}}' +
                        '</option>' +
                      '</select>' +
                    '</div>',
        link: function(scope, element, attrs) {}
    }
}]);

控制器

currentApp.controller('ACtrl', function($scope){

          $scope.templates = {
            pages: ['home', 'about'],
            posts: ['blog', 'lab']
          };
});

JSFIDDLE

【讨论】:

  • 什么时候必须使用 $compile 有简短的回答吗?
  • 我不在。很高兴你找到了解决方案:)
  • 嘿,dcodesmith,你认为你能解释为什么编译函数是用一个数组来编写的吗?我很难找出这是如何以及为什么起作用的。我真的不想再问这样的问题了。为什么不能使用 $scope 语法,如 currentApp.directive('formControl', function ($compile) {});
  • 哦!这不是问题,您可以按照自己的方式使用它。但是,假设您想在注入 $compile 后重命名它,那么您就可以拥有它。所以你会有 $compile 然后在函数参数中使用 compile 或者你想给它的任何其他变量名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多