Directive with <select ng-options> and indirection

后端 未结 1 810
无人共我
无人共我 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:
            '
    ' + '' + '
    ' + '
    ' + '' + '
    ' + '
    ' + '
    ', 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
    
      Users
    
    

    I've updated the plunkr with the compile function.

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