动态添加angularjs指令 [英] dynamically adding angularjs directives

查看:129
本文介绍了动态添加angularjs指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个指令,动态地添加另一种类型的指令,以DOM和编译它们。看来使用字符串模板时的工作,但使用templateUrl时失败。这里的工作模板字符串的的jsfiddle:

  app.directive('唱首歌,函数($编译){
    使用严格的;    返回{
        编译:功能(tElement,tAttrs){
            变种T ='< D​​IV数据流行GT;流行LT; / DIV>';            返回功能(范围,iElement){
                iElement.click(函数(){
                    $(身体)追加($编译(T)(范围))。
                });
            };
        }
    }
});app.directive('流行',函数(){
    使用严格的;    返回{
        模板:'< D​​IV>测试模板< / DIV>'
        // templateUrl:'谐音/ pop.html
    };
});

http://jsfiddle.net/89AYX/

但如果换到templateUrl(一个HTML文件,其中包含什么是模板字符串),它只会工作的一次的。它的元素添加到DOM,但它不包含templateUrl内容,也没有调用动态添加的指令链接功能...

试图增加他们两个会使得DOM看起来是这样的:

 < D​​IV数据流行GT;<! -  pop.html内容 - >< / DIV>
< D​​IV数据流行GT;< / DIV>
< D​​IV数据流行GT;< / DIV>


解决方案

添加范围。$适用()为我工作。经测试使用jQuery 1.9.0和1.0.3角

  iElement.bind('点击',功能(){
    $(身体)追加($编译(T)(范围))。
    。范围$适用(); //引起消化$循环运行,因为我们是外角
});

小提琴使用内联的模板,但我还与当地的网络服务器是不得不做测试一个单独的HTTP GET来获得部分。

I'm trying to write a directive that dynamically adds directives of another type to the DOM and compile them. It seems to work when using a string template, but fails when using templateUrl. Here's a jsfiddle of the working template string:

app.directive('clicker', function($compile) {
    'use strict';

    return {
        compile: function(tElement, tAttrs) {
            var t = '<div data-pop>Pop</div>';

            return function(scope, iElement) {
                iElement.click(function() {
                    $('body').append($compile(t)(scope));
                });
            };
        }
    }
});

app.directive('pop', function() {
    'use strict';

    return {
        template: '<div>Testing template</div>'
        //templateUrl: 'partials/pop.html'
    };
});

http://jsfiddle.net/89AYX/

But if swapped to templateUrl (with an html file containing exactly what's in the template string) it will only work once. It does add an element to the DOM but it does not contain the templateUrl contents nor does it call the linking function in the dynamically added directive ...

Trying to add two of them will make the DOM look something like:

<div data-pop><!-- content of pop.html --></div>
<div data-pop></div>
<div data-pop></div>

解决方案

Adding scope.$apply() worked for me. Tested with jQuery 1.9.0 and Angular 1.0.3.

iElement.bind('click', function() {
    $('body').append($compile(t)(scope));
    scope.$apply();  // cause a $digest cycle to run, since we're "outside" Angular
});

This fiddle uses an inlined template, but I also tested with a local webserver that had to do a separate HTTP GET to get the partial.

这篇关于动态添加angularjs指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆