如何创建angularjs动态指令? [英] How to create dynamic directive in angularjs?

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

问题描述

我有这样的HTML和指令:

I have this html and directive:

HTML

<div id="box">
    <button test>Add</button>
</div>

和这个指令:

// directive for button
tarefasApp.directive('test', function($compile){
    return function(scope, element, attrs){
        element.bind('click', function(){
            // create anchor
            el      = document.createElement('a');
            el.id   = 'test2';
            el.innerHTML = 'Click me';
            att     = document.createAttribute('test2');

            // set attribute to anchor
            document.getElementById('test2').setAttributeNode(att);

            // insert the anchor inside div#box
            document.getElementById('box').appendChild(el);
        });
    }
});

// directive for the dynamically created anchor
tarefasApp.directive('test2', function($compile){
    return function(scope, element, attrs){
        element.bind('click', function(){
            alert('it worked!');
        });
    }   
});

当我点击&LT;按钮试验&gt;&LT; /按钮&GT; ,第一个指令创建一个&LT;一个ID =测试2测试2&GT ;点击ME&LT; / A&GT; 并将其附加到&LT; D​​IV ID =盒子&GT;&LT; / DIV&GT; 。到现在为止还挺好。但是,当我点击&LT;一个ID =测试2测试2&gt;点击ME&LT; / A&GT; 它不叫指令测试2 ,我不知道为什么。我在做什么错了?

When I click <button test></button>, the first directive creates a <a id="test2" test2>Click me</a> and append it to <div id="box"></div>. So far so good. But when I click <a id="test2" test2>Click me</a> it doesn't call the directive test2 and I don't know why. What am I doing wrong?

推荐答案

什么是你想实现什么呢?

What are you trying to accomplish exactly?

我做的如何使一个新的HTML元素,编译它与角$编译一次你在DOM中添加一个例子

I made an example of how to make a new HTML element, and "compile" it with the angular $compile once you add it in the DOM

的http://$c$cpen.io/AntouanK/pen/irkHL

var tarefasApp =
angular.module('tarefas', []);

// directive for button
tarefasApp
.directive('test',
['$compile',
function($compile){

    return {
      restrict: 'A',
      link: function(scope, element, attrs){

        element
        .on('click',function(){

          var newAnchorEle;

          //  make the new element
          newAnchorEle = document.createElement('a');

          angular.element(newAnchorEle)
          .attr('anchor', '')
          .text('test');

          //  append it in the parent element
          element.parent().append(newAnchorEle);
          //  compile the new HTML
          $compile(newAnchorEle)(scope);
        });
      }
    }
}]);

// directive for the anchor
tarefasApp
.directive('anchor',
['$compile',
function($compile){

    return {
      restrict: 'A',
      link: function(scope, element, attrs){

        console.log('anchor made');

        setInterval(function(){
          element.toggleClass('hidden');
        },500);
      }
    }
}]);

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

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