【问题标题】:Create an AngularJS directive that does not immediately render?创建一个不会立即呈现的 AngularJS 指令?
【发布时间】:2013-07-16 01:21:02
【问题描述】:

我有一个简单的AngularJS directive with a templateUrl。该指令用于工具提示。

  • 目前我附加了一个隐藏元素。然而,该指令的使用非常频繁,因此 会发生数百个数据 DOM 绑定,并且页面会变慢到无法使用的程度
  • 我只想实际加载模板,并在鼠标悬停时附加元素。

Reading the angular docs, there doesn't seem to be any way of making a directive delay rendering。我错过了什么吗?

   

    // Tooltip directive
    return function(){
        return {
        templateUrl: 'someTemplate.html',
        replace: false, // Append our tooltip, rather than replace the element's contents.
            link: function (scope, element, attrs) {
                $element.on({
                mouseenter: function () {
                    // Would like to render, and set up bindings, here (my question)
                    },
                mouseleave: function () {
                    // Destroy rendered element here (simple stuff, not my question)
                    }
                });
            }
        }   
    }

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    我相信你需要注入 $compile 服务来在你的回调中做这样的事情:

    templateMarkup = '<p> {{ property }} </p>';
    $compile(templateMarkup)(scope);
    

    我还没有考虑过将其放入您的代码中的确切步骤,但如果这会有所帮助,请告诉我。

    【讨论】:

    • 感谢您的回答!我考虑过 $compile,这将解决第二个问题,即如何按需渲染弹出窗口,但是如何防止 Angular 一开始就立即渲染?
    • 简而言之,不要为指令声明模板。如果你这样做了,Angular 将控制它何时被编译离开你(并预先编译它)。或者,您可以将标记添加为模块值 angular.module('myApp', []).value('popupMarkup', '&lt;p&gt;{{property}}&lt;/p&gt;'); 并将其注入您的链接函数中。或者,如果您不想太花哨,可以将该标记声明为指令中的字符串变量。
    猜你喜欢
    • 2011-07-19
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2017-01-03
    相关资源
    最近更新 更多