angularjs-directive - 创建包含其他指令的 Angular.js 指令

标签 angularjs-directive angular-ui

我正在尝试提出一个可重用指令库。我尝试实现的前两个指令是 DatePicker 和 DateRangePicker。 DateRangePicker 必须包含两个 DatePicker。

我希望 DatePicker 具有类似于以下内容的签名:

<div cx-date-picker="" cx-label="myLabel" 
     cx-id="myDate" cx-source="myDateVarInScope"></div>

我希望 DateRangePicker 看起来像这样:
<div cx-date-range-picker cx-id="searchRangePicker" 
     cx-source="myDateRangeInScope"></div>

其中myDateRangeInScope包含的成员:的startDate和结束日期

我查看了一些有关如何创建指令的示例,但我无法弄清楚如何将参数传递给底层指令。这是 DatePicker 的代码
angular.module('ng').directive('cxDatePicker', function () {
      return {
        restrict: 'A',
        scope: 'isolate',
        template: '<div class="control-group input-append">' +
        '<label for="{{theId}}" class="label">{{theLabel}}</label>' +
        '<input id="{{theId}}" class="input-small" type="text" ' + 
        'ng-model="theSource" data-date-format="dd/mm/yyyy" bs-datepicker>' +
        '<button type="button" class="btn" data-toggle="datepicker">' +
        '<i class="icon-calendar"></i></button>' +
        '</div>',

        link: function (scope, iterStartElement, attr) {
          var theId = attr['cxId'];
          scope.theLabel = attr['cxLabel']
          scope.theId = attr['cxId'];
          scope.theSource = attr['cxSource'];
        }
      };
    });

它显示了 theId 和 theLabel 的正确值,但没有显示正确的日期。

这是 DateRangePicker 的代码,它无法为基础 DatePicker 设置属性。
angular.module('ng').directive('cxDateRangePicker', function () {
      return {
        restrict: 'A',
        scope: 'isolate',
        template: '<div cx-date-picker="" cx-source="{{startSource}}" ' +
          'cx-label="{{fromLabel}}" cx-id="{{startId}}"></div>' +
          '<div cx-date-picker="" cx-source="{{endSource}}" cx-label="{{toLabel}}" ' +
          ' cx-id="{{endId}}"></div>',
        link: function (scope, iterStartElement, attr) {
          var theId = attr['cxId'];
          scope.startId = theId + "From";
          scope.endId = theId + "To";
          scope.fromLabel = "From";
          scope.toLabel = "To";
          scope.startSource = attr['cxSource'] + ".startDate";
          scope.endSource = attr['cxSource'] + ".endDate";

        }
      };
    });

任何人都可以指出我的解决方案吗?我看到底层 DatePicker 的 link() 方法在 DateRangePicker 的 link() 方法之前被调用。因此,难怪没有传递这些值。但我缺乏解决问题的整体概念理解。官方文档没有多大帮助。

一般来说,有没有人尝试实现类似的目标——在其他指令之上构建指令,并通过这样做来构建特定于业务领域的组件库?

最佳答案

关键在于正确使用示波器。
@ 属性只是静态地从标签属性复制值,而您应该使用 = 将父作用域变量与指令作用域变量联系起来的属性。
我创建了 this plunker向您展示如何正确实现这两个指令。

关于angularjs-directive - 创建包含其他指令的 Angular.js 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868990/

相关文章:

angularjs - 如何正确清理 Angular 指令的子范围

javascript - Angular ui-select 标记在模糊时丢失文本输入

javascript - Angular UI Select-UI 未更新选择模型?

angularjs - 条件 ui View

javascript - 具有隔离范围的指令内的 Angular 形式

javascript - 指令回调和范围

angularjs - 当replace=true时如何防止angular指令中的重复属性

angularjs - 如何在 ui-select 中使用 Selectize 主题?

css - ui-bootstrap 滚动标签 : prevent first tab from moving

javascript - 如何动态设置元素的高度?