【问题标题】:How to create reusable custom directives in angular JS如何在 Angular JS 中创建可重用的自定义指令
【发布时间】:2025-12-28 19:25:11
【问题描述】:

如何在 AngularJS 中创建可重用的模型窗口?

我希望它是可重用的,因为我们使用超链接触发模态窗口并根据传递的参数设置弹出内容。例如:

<div ng-controller="SampleCtrl">
    <a ng-click="toggleModal('FirstParam')">first</a>
    <a ng-click="toggleModal('SecondParam')">second</a>
    <a ng-click="toggleModal('ThirdParam')">Third</a>
</div>

当第一个链接被点击时,它会显示一个包含“FirstParam”等相关内容的模式。

我尝试过自定义指令并使用$parent,但我不知道如何将参数从toggleModal 函数调用传递到自定义指令。

如何实现类似于this example 的可重复使用的模态窗口?

我特别想知道:

  • 如何将变量从控制器函数传递到自定义指令?
  • 有没有关于可重用自定义指令和作用域的好教程?
  • 还有其他可重用自定义指令的设计模式吗?

【问题讨论】:

  • @Martin Atkins 感谢编辑

标签: angularjs angularjs-directive


【解决方案1】:

查看http://egghead.io 了解有关编写自定义指令的一些基础知识,有关指令和编译的角度文档也包含所有详细信息https://docs.angularjs.org/guide/directive https://docs.angularjs.org/api/ng/service/$compile

这是我发布的一个 plnkr,其中包含 ui-bootstrap 的弹出框的覆盖模板。根据您的具体用例,您可能只需覆盖模板或制作使用 $modal 或其他模式 UI 控件的指令http://plnkr.co/edit/eeiJ5re7mNdhHNDEeCQO?p=preview

// Code goes here

angular.module("myApp", ["ui.bootstrap", "ngSanitize"]).controller("TestCtrl", function($scope){


})

angular.module("template/popover/popover.html", []).run(["$templateCache", function ($templateCache) {
        $templateCache.put("template/popover/popover.html",
            "<div class='popover {{placement}}' ng-class='{ in: isOpen(), fade: animation() }'>" + 
            "<div class='arrow'></div><div class='popover-inner'>" + 
            "<h3 class='popover-title' ng-bind='title' ng-show='title'></h3>" + 
            "<div class='popover-content' ng-bind-html='content'></div>" +
            "<button class='btn btn-cancel' ng-click='manualHide()'>Cancel</button>" +
            "<button class='btn btn-apply' ng-click='manualHide()'>Apply</button></div></div>");
    }]);

【讨论】:

  • 感谢您的回答。我已经浏览了 angularjs.org 和自定义指令,但是我对“如何将参数从控制器传递到指令‘链接’函数”感到震惊,如果我知道这一点,我会根据超链接动态加载模板。
  • 基本上你只需要阅读编译文档中关于范围定义细节的细节
最近更新 更多