Directive with <select ng-options> and indirection

后端 未结 1 807
无人共我
无人共我 2021-01-25 13:56

I have several multi-selects on a page, each with a bit of logic that fills that multi-select from the server, and I want to wrap each one up into a Directive.

Before tr

相关标签:
1条回答
  • 2021-01-25 14:35

    The main problem with your directive is that you can't use mustache binding in ngModel and ngOptions directive because they are evaluated directly. You can directly bind to the scoped property (ngModel and alloptionsModel):

    directive('dimension', function() {
      return {
        restrict: 'E',
        scope: {
          ngModel: '=',
          alloptionsModel: '='
        },
        template:
            '<div>' + 
              '<label ng-transclude></label>' +
              '<fieldset>' +
                  '<div class="form-group">' +
                    '<select ng-model="ngModel" ng-options="x for x in alloptionsModel" multiple class="form-control"></select>' +
                  '</div>' +
               '</fieldset>' +
            '</div>',
        replace: true,
        transclude: true
      };
    });
    

    See this plunkr for a working example.

    Edit As for the compile route, there is nothing wrong with it. It is useful when you need to dynamically create a template which will clearly be your case when you will get to the select's item template.

    compile: function(tElement, tAttrs) {
      var select = tElement.find('select'),
          value = tAttrs.value ? 'x.' + tAttrs.value : 'x',
          label = tAttrs.label ? 'x.' + tAttrs.label : 'x',
          ngOptions = value + ' as ' + label + ' for x in alloptionsModel';
    
          select.attr('ng-options', ngOptions);
    }
    
    // In the HTML file
    <dimension ng-model="inputs.users" 
               alloptions-model="allusers"
               label="name">
      Users
    </dimension>
    

    I've updated the plunkr with the compile function.

    0 讨论(0)
提交回复
热议问题