Assign directive attributes to an element in template

前端 未结 1 868
暖寄归人
暖寄归人 2021-01-21 10:23

I have a directive which is supposed to make my select a little fancier:

angular.module(\'myDeadLine\')

    .directive(\'dcSelect\', function () {
        retur         


        
相关标签:
1条回答
  • 2021-01-21 10:46

    It is the valid scenario, but the resistance from Angular doesn't make it a trivial task to do. Usually replace: true is used to transfer all the attributes to the child template element. But select isn't a direct descendant, it is not an option.

    The other possibility is to use terminal: true in conjunction with high priority, because ng-model, ng-options and any other attribute directives shouldn't be compiled on dc-select element. But terminal: true would also stop the bindings from working (in this case they have to be interpolated manually).

    I guess the easiest way is

    .directive('dcSelect', function ($compile) {
        return {
            restrict: 'E',
            scope: {
                label: '@',
                dcNgModel: '=',
                dcNgOptions: '='
            },
            transclude: true,
            templateUrl: '/web/_utils/dcselect/dcselect.html',
            link: function (scope, element, attrs) {
              var select = element.find('select');
    
              angular.forEach(attrs.$attr, function (name, normalizedName)  {
                if (!name.match(/^dc-/)) return;
    
                var val = scope.hasOwnProperty(normalizedName) ? normalizedName : element.attr(name);
                select.attr(name.replace(/^dc-/, ''), val);
              });
    
              $compile(select)(scope);
            }
        };
    });
    
    0 讨论(0)
提交回复
热议问题