【问题标题】:Assign directive attributes to an element in template将指令属性分配给模板中的元素
【发布时间】:2015-09-18 17:18:52
【问题描述】:

我有一个指令应该让我的选择更有趣:

angular.module('myDeadLine')

    .directive('dcSelect', function () {
        return {
            restrict: 'E',
            scope: {
                label: '@',
                ngModel: '=',
                ngOptions: '=',...
            },
            transclude: true,
            templateUrl: '/web/_utils/dcselect/dcselect.html'
        };
    });

使用模板:

<div class="form-group">
    <select class="form-control"
            ng-focus="dcSelectFocused=true"
            ng-blur="dcSelectFocused=false">
        <option value="">{{label}}</option>
    </select>
    <i class="fa fa-arrow-down" ng-class="{ 'open': dcSelectFocused }"></i>
</div>

将所有与选择相关的属性分配给选择标签的最简单方法是什么,以便我可以像这样使用它:

<dc-select label="Select something" ng-model="model" ng-options="" and so on></dc-select>

有没有一种自动化的方式可以让我将所有属性转移到“标签”之外的选择,并让它们发挥作用?

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

这是一个有效的场景,但来自 Angular 的阻力并没有使它成为一项微不足道的任务。通常replace: true 用于将所有属性传递给子模板元素。但是select 不是直系后代,也不是一个选项。

另一种可能性是将terminal: true 与高priority 结合使用,因为ng-modelng-options 和任何其他属性指令不应该在dc-select 元素上编译。但是terminal: true 也会阻止绑定工作(在这种情况下,它们必须手动插入)。

我想最简单的方法是

.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);
        }
    };
});

【讨论】:

  • 很好的答案。谢谢你。明天将广泛研究。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
  • 2013-10-28
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多