【问题标题】:Angular.js - Wrapper directive around existing select directiveAngular.js - 围绕现有选择指令的包装器指令
【发布时间】:2013-11-01 04:17:54
【问题描述】:

我已经使用一些标记、css 和没有任何 javascript 的常规选择元素制作了一个自定义选择下拉列表,但我想将其设为 angularjs 指令,这样我就不必在我的应用程序中不断重复样板 html .这是使用的标记示例(还没有 angularjs 的东西)

<div class="select">
  <select name="mySelect">
    <option value="val1">Value 1</option>
    <option value="val2">Value 2</option>
    <option value="val3">Value 3</option>
  </select>
  <span class="select-value">Value 1</span>
  <span class="select-arrow"><i></i></span>
</div>

我希望能够做类似的事情

<my-select ng-model="mySelect" ng-options="opt.val as opt.label for opt in options">

类似于我使用内置选择指令的方式。有没有一种简单的方法来包装或扩展 select 指令,同时保留它的功能?

谢谢!

【问题讨论】:

  • 您是否尝试过在其模板中使用 ng-select 创建指令?
  • 我已经考虑过了,但我不确定使用 ng-options 的数据绑定是否会出现问题。不过我会试一试
  • 我现在试了一下,我能看到的唯一选项是在模板中使用字符串操作或锁定 ng-options 以仅使用指定的数据类型,我'我宁愿不这样做。

标签: angularjs angularjs-directive


【解决方案1】:

Using a decorator 将允许您修改指令,甚至是内置指令。例如:

angular.module('directiveDecoration', [])
    .config(['$provide', Decorate]);

function Decorate($provide) {

  //decorate angular's built-in select directive
  $provide.decorator('selectDirective', ['$delegate', function($delegate) {
    var directive = $delegate[0],
      link = directive.link;

    //directive.templateUrl = "test/something.tpl.html";

    directive.compile = function() {
      return function(scope, element, attrs, ctrl) {
        link.apply(this, arguments);

        //do more  stuff here...
      }
    };

    return $delegate;
  }]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多