Domanda

Explanation:

I would like to use one ng-repeat directive, that goes over a nested JavaScript object called $scope.templates to create and populate a form's labels and fields.


Current code uses multiple ng-repeats and hardcoded labels, to get expected results:

JSbin Link

JS:

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

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

          };

     });

I would like to use pages: and posts: as the labels and the array[] as the <options> to the select menu

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>

Here's the JSbin

È stato utile?

Soluzione

HTML

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

DIRECTIVE

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) {}
    }
}]);

CONTROLLER

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

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

JSFIDDLE

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top