Angularjs:理解递归指令

2024-03-28

我在这里找到了一个很棒的树指令。原来的:http://jsfiddle.net/n8dPm/ http://jsfiddle.net/n8dPm/

我一直试图通过其他几个问题来理解它的功能,1 https://stackoverflow.com/questions/19120386/angularjs-transclude-directive-template,2 https://stackoverflow.com/questions/19124986/angularjs-attaching-a-click-event-in-directive。我不太明白渲染树指令的递归调用是如何工作的。主要是编译功能

  1. 所有compile函数什么时候调用?
  2. $compile函数什么时候缓存在变量中compiledContents(这是链接函数吗?),什么时候追加?为什么不总是追加?

--

compile: function(tElement, tAttr) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone); 
                });
            };
        },

Ng 网站有一些很棒的文档(我认为其中一些是最好的)。启动和运行时循环的概述非常有帮助:http://docs.angularjs.org/guide/concepts http://docs.angularjs.org/guide/concepts

在较高的层面上,当 Ng 第一次启动时,它会从 ng-app 所在的位置开始编译 DOM(就像 Ng 的另一个指令一样)。这意味着它会遍历元素并查找链接到 $rootScope 所需的指令和表达式(所有作用域的根,是编译/链接过程设置的原型继承链的一部分)。如果它是一个指令,编译过程也会对其进行。编译过程会获取在 HTML 中找到的所有 Ng 指令,并根据分配的优先级对它们进行优先级排序,或者假设优先级为零。当它们全部排序后,它会执行返回链接函数的指令的编译函数。在上面的示例中,有两个显示链接函数,我将在下面对其进行注释以及将其链接到此说明的其他注释。链接函数还以嵌入对象的形式给出指令所在元素中的 HTML,该元素是属性、类或元素。

执行链接函数,链接作用域和指令并生成视图。这可能包括 HTML/transclude,因此可以将其添加到指令模板中的指令 ng-transclude 所在的位置(该指令将应用相同的过程,其模板是嵌入)。

以下是我对上面稍微修正的自定义指令的注释:

module.directive("tree", function($compile) {
    //Here is the Directive Definition Object being returned 
    //which is one of the two options for creating a custom directive
    //http://docs.angularjs.org/guide/directive
    return {
        restrict: "E",
        //We are stating here the HTML in the element the directive is applied to is going to be given to
        //the template with a ng-transclude directive to be compiled when processing the directive
        transclude: true,
        scope: {family: '='},
        template:       
            '<ul>' + 
                //Here we have one of the ng-transclude directives that will be give the HTML in the 
                //element the directive is applied to
                '<li ng-transclude></li>' +
                '<li ng-repeat="child in family.children">' +
                    //Here is another ng-transclude directive which will be given the same transclude HTML as
                    //above instance
                    //Notice that there is also another directive, 'tree', which is same type of directive this 
                    //template belongs to.  So the directive in the template will handle the ng-transclude 
                    //applied to the div as the transclude for the recursive compile call to the tree 
                    //directive.  The recursion will end when the ng-repeat above has no children to 
                    //walkthrough.  In other words, when we hit a leaf.
                    '<tree family="child"><div ng-transclude></div></tree>' +
                '</li>' +
            '</ul>',
        compile: function(tElement, tAttr, transclude) {
            //We are removing the contents/innerHTML from the element we are going to be applying the 
            //directive to and saving it to adding it below to the $compile call as the template
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {

                if(!compiledContents) {
                    //Get the link function with the contents frome top level template with 
                    //the transclude
                    compiledContents = $compile(contents, transclude);
                }
                //Call the link function to link the given scope and
                //a Clone Attach Function, http://docs.angularjs.org/api/ng.$compile :
                // "Calling the linking function returns the element of the template. 
                //    It is either the original element passed in, 
                //    or the clone of the element if the cloneAttachFn is provided."
                compiledContents(scope, function(clone, scope) {
                        //Appending the cloned template to the instance element, "iElement", 
                        //on which the directive is to used.
                         iElement.append(clone); 
                });
            };
        }
    };
});

整个工作正常:http://jsfiddle.net/DsvX6/7/ http://jsfiddle.net/DsvX6/7/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angularjs:理解递归指令 的相关文章

  • 将数组中的所有值作为参数传递给函数

    我有一个值数组 a b c d 我需要将它们作为参数传递给函数 window myFunction a b c d 如果我可以将数组 对象传递到函数中 那么这会更容易 但这些函数是由其他人编写的或已经存在 我无法更改它们 它们需要作为单独的
  • 单击菜单外部以关闭菜单时,Bootstrap 导航栏“闪烁”

    我遇到了导航栏问题 当您单击菜单外部以关闭菜单时 导航栏会出现 闪烁 如果在单击菜单外时按住鼠标 则闪烁会持续存在 如下所示 我认为这可能与角度有关 而不是与CSS有关 主要是因为其他人未能在小提琴上复制它 上一个问题在这里 https s
  • triggerHandler 导致错误:[$rootScope:inprog] $apply 已进行中错误 - AngularJS

    我试图在按下某个键时触发按钮的单击 我正在使用triggerHandler函数 但这导致了上述错误 我想我一定创建了某种循环引用 循环 但我看不到在哪里 这是我的 HTML
  • Jquery 动画与 CSS 浮动

    我的代码有问题 宽度似乎可以工作 但浮动没有 这里是 这是一个例子 http jsfiddle net v82ck http jsfiddle net v82ck 问题 悬停时菜单上的浮动属性不会改变 我希望每个菜单元素下方的线在悬停该菜单
  • 对 JavaScript 中的 while 循环感到困惑

    我可能在这里有点厚重 但请回答我这个问题 考虑以下代码 a 1 while a lt 6 console log a a 如果我运行这个 我会在控制台中得到从 1 到 6 的值 然后是另一个 6 现在看看这个 a 1 while a lt
  • angular.copy() 和 JSON.parse(JSON.stringify()) 之间的区别?

    有人可以解释 angular copy 和 JSON parse JSON stringify 之间的区别吗 有吗 您会推荐使用什么 angular fromJson angular toJson 与 JSON parse JSON str
  • Chart.js 没有显示在我的视图中

    我有一个使用 angular js 运行的应用程序 我的视图之一应该加载图表 我正在使用 Chart js 但由于某种原因它不起作用 并且我的控制台上没有显示错误 这是我创建图表的函数 scope writeBatteryChart fun
  • 嵌套对象的 AJV 模式验证

    函数返回的对象看起来像这样 answer vehicle type 1 message Car model VW color red 答案 对象始终存在 其他字段基于 vehicle type E g 如果vehicle type 1 则有
  • 按自定义字母顺序对数组进行排序

    如何对这样的数组进行排序 apple very auto tom tim violet 要按 v a t x b 等排序 不按字母顺序 violet very auto tom tim 在脚本中 我会做这样的事情 myArray sort
  • Backbone-relational 无法实例化两个 RelationalModel 对象

    我正在尝试实现 BackboneRelational 并不断获得 无法实例化多个 Backbone RelationalModel 每种类型都有相同的 ID class App Models User extends Backbone Re
  • 在 NPM 上捆绑并发布客户端 Web 代码

    我制作了一个 JavaScript 文件 假设它的内容是这样的 let myCoolAlert str gt alert str in a different js file SO doesn t allow you to cross fi
  • 避免 AngularJS 部分视图在 IE 中缓存

    我正在开发一个 ASP NET MVC 应用程序 它也有一些 angularJS 我有一个主页 其中有不同的选项卡 当您单击它们时 它们会加载角度部分视图 主页是这样的 div class widget div div class widg
  • 获取键盘事件中的鼠标位置

    我试图在用户按住 Shift 键时出现选择轮 滚轮应以鼠标位置为中心 然而当我测试这个时 pageX and clientX两者在事件对象上都未定义 是否可以通过键盘事件获取鼠标坐标 不 只需跟踪mousemove事件并持续保存当前位置 以
  • 日期时间的自定义 JavaScriptConverter?

    我有一个对象 它有一个 DateTime 属性 我想通过 AJAX JSON 将该对象从 ashx 处理程序传递回网页 我不想使用第 3 方控件 当我这样做时 new JavaScriptSerializer Serialize DateT
  • HTML if 语句在 CDN 失败时加载本地 JS/CSS

    当从 CDN 或任何外部服务器加载 CSS JS 文件时 有可能 即使概率很低 由于外部故障而丢失该文件 在这种情况下 html 页面将因缺乏适当的 CSS 和 JS 而被损坏 有没有一种实用的方法可以在 CDN 故障时加载本地版本 IF
  • 反转二进制网络

    如何反转二元方程 以便找到哪些输入将产生给定的输出 Example Inputs i0 through i8 Outputs o0 through o8 Operators XOR AND 二元方程 1 i0 1 i1 0 i2 1 i3
  • JavaScript - 这个这个

    String prototype foo String prototype foo bar function How can you reference the grandparent string console log this par
  • CKEditor TypeError:c[a] 在 CodeIgniter 中未定义

    我正在尝试在基于 codeigniter 的网站中安装 CKEditor 并且我已按照本教程进行操作 Codeigniter 教程中的 CKEditor http nukium com developpement php framework
  • 可选链接在 create-react-app 中不起作用

    In a create react app项目 我正在使用 babel plugin proposal optional chaining在我的 babelrc中 但是 我有这个错误 Module parse failed Unexpect
  • 使用 Promise 语法编写同步代码有什么好处吗?

    有同步承诺这样的概念吗 使用 Promise 语法编写同步代码有什么好处吗 try foo bar a b bam catch e handleError e 可以写成类似的东西 但使用同步版本then foo then bar bind

随机推荐

  • 在固定超时内缓存单个对象的最佳方法是什么?

    Google Guava 有 CacheBuilder 允许使用过期密钥创建 ConcurrentHash 从而允许在固定 tiemout 后删除条目 但是我只需要缓存某种类型的一个实例 使用 Google Guava 在固定超时内缓存单个
  • Rxjs 主题下一个或 onNext

    我对 rxjs 很陌生 请耐心等待 例如在本教程中http blog angular university io how to build angular2 apps using rxjs observable data services
  • 无法在 Ubuntu 12.10 上安装 pg gem

    我使用的是 Ubuntu 12 10 64 位 并且安装了以下软件包 dpkg get selections grep postgre output postgresql postgresql 9 1 postgresql client p
  • 在 Java 中对月份和年份进行排序的最有效方法

    我有一个列表 其中包含字符串格式的日期 MON YYYY 我需要对此列表进行排序 到目前为止我遵循的方法是读取列表并以日期格式转换字符串并使用比较选项 但是我我没有得到想要的结果 代码片段 List
  • 检测受密码保护的 PPT 和 XLS 文档

    我找到了这个答案https stackoverflow com a 14336292 1537195 https stackoverflow com a 14336292 1537195这提供了检测 DOC 和 XLS 文件密码保护的好方法
  • 追加在 for 循环中生成的 pandas 数据帧

    我正在 for 循环中访问一系列 Excel 文件 然后我将 Excel 文件中的数据读取到 pandas 数据框中 我不知道如何将这些数据框附加在一起 然后将数据框 现在包含所有文件中的数据 保存为新的 Excel 文件 这是我尝试过的
  • Python Reddis 队列 ValueError:worker 无法处理 __main__ 模块中的函数

    我正在尝试使用 python rq 在 redis 中排队一项基本作业 但它会抛出此错误 ValueError 函数来自main模块无法被工作人员处理 这是我的程序 import requests def count words at ur
  • Oracle:DDL 和事务回滚

    Oracle DDL 创建 更改 是否可以像 MS SQL 中那样具有事务性 从 2005 年开始 DDL 在 Oracle 中不是事务性的 来自11 2 doc http docs oracle com cd E25054 01 serv
  • 使用 javascript regexp 查找第一个和最长的匹配

    我有一个像下面的简化示例一样的正则表达式 var exp he hell 当我在字符串上运行它时 它会给我第一个匹配项 fx var str hello world var match exp exec str match contains
  • 将 CNN 的输出传递给 BILSTM

    我正在开发一个项目 其中我必须将 CNN 的输出传递给双向 LSTM 我创建了如下模型 但它抛出 不兼容 错误 请让我知道哪里出了问题以及如何解决这个问题 model Sequential model add Conv2D filters
  • requestAnimationFrame 仅被调用一次

    我正在尝试在 Ionic 2 应用程序中使用 ThreeJS 实现非常基本的动画 基本上是尝试旋转一个立方体 但立方体没有旋转 因为 requestAnimationFrame 仅在渲染循环内执行一次 I m able to see onl
  • 如何设置 Eclipse CDT 使用 GCC-4 而不是 GCC?

    如何设置 Eclipse CDT 使用 GCC 4 而不是 GCC 我问这个问题是因为我使用 Windows 64 位和 Cygwin 而 gcc exe 不起作用 我需要配置 Eclipse CDT 以使用 gcc 4 exe 但我不知道
  • 将 CSV 文件或 Excel 电子表格转换为 RESX 文件

    我正在寻找针对我遇到的问题的解决方案或建议 我有一堆需要本地化的 ASPX 页面 还有一堆需要支持 6 种语言的文本 进行翻译的人员无法访问 Visual Studio 最简单的工具可能是 Excel 如果我们使用 Excel 甚至导出到
  • 带有 firebase crashlytics 的 Hermes 包的反应本机源图

    我想从react native应用程序中读取crashlytics报告 但它在firebase控制台中根本不可读 Android 的崩溃示例如下所示 Non fatal Exception io invertase firebase cra
  • 使用 AST 解析器提取类实现的接口

    我正在使用 AST 解析器编译项目源代码 我可以通过什么方式提取类层次结构信息 即它是否正在实现任何接口或从另一个类扩展 您可以访问TypeDeclaration节点并从中获取类型绑定 ITypeBinding typeBind typDe
  • Scala,让我的循环更加实用

    我正在尝试减少像 Java 一样编写 Scala 2 8 的程度 这是我遇到的问题的简化 您能否对我的解决方案提出 更实用 的改进建议 变换地图 val inputMap mutable LinkedHashMap 1 gt a 2 gt
  • 在 Bash 中执行时间戳比较的最佳方法是什么

    我有一个警报脚本 我试图阻止它向我发送垃圾邮件 因此我想设置一个条件 如果在过去一小时内发送了警报 则不再发送警报 现在我有一个 cron 作业 每分钟检查一次条件 因为我需要在满足条件时快速收到警报 但我不需要每分钟都收到电子邮件 直到问
  • Spark - 是否可以控制分区到节点的放置?

    在 Spark 中 自定义Partitioner可以为 RDD 提供 通常 生成的分区会随机分配给一组工作人员 例如 如果我们有 20 个分区和 4 个工作线程 则每个工作线程将 大约 获得 5 个分区 然而 放置分区到工作节点 节点 看起
  • 将 ChartPanel 添加到 JPanel

    我这里有一些不起作用的代码 XYSeriesCollection dataset new XYSeriesCollection dataset addSeries series JFreeChart chart ChartFactory c
  • Angularjs:理解递归指令

    我在这里找到了一个很棒的树指令 原来的 http jsfiddle net n8dPm http jsfiddle net n8dPm 我一直试图通过其他几个问题来理解它的功能 1 https stackoverflow com quest