简体   繁体   English

在动态生成的DOM中添加Angular自定义指令?

[英]Adding an Angular custom directive to dynamically generated DOM?

I am using a JavaScript library called "Treant.js" to dynamically generate a tree structure. 我正在使用一个名为“ Treant.js”的JavaScript库来动态生成树结构。

Because the DOM elements responsible for the tree structure are dynamically generated as SVG by the Treant.js library, I do not have direct access to those elements at all. 因为负责树结构的DOM元素是由Treant.js库动态生成为SVG的,所以我根本无法直接访问这些元素。

Here is what the HTML looks like 这是HTML的样子

<div class="node nodeBranches>
    <p class="node-name>TEXT</p>
</div>

This block of codes gets added to the tree DOM whenever a new data is added via form. 每当通过表单添加新数据时,此代码块就会添加到树DOM中。

Here is the code that I came up with in order to add "ng-class" directive to the div whose class is node. 这是我想出的代码,用于向类为node的div添加“ ng-class”指令。

var target = angular.element(".nodeBranches");
for (var i = 0; i < target.length; i++) {
    target.eq(i).attr("ng-class", "changeClass()");
}

Looking at the developer's tool in chrome, I see that the custom attribute "ng-class" is added to each div.node, but the functionality is not there. 查看chrome中的开发人员工具,我看到自定义属性“ ng-class”已添加到每个div.node,但是功能不存在。

The same thing happens for "ng-click" attribute as well. “ ng-click”属性也会发生相同的情况。 I can see the custom directive in the code, but it does not work. 我可以在代码中看到自定义指令,但是它不起作用。

How can I make this work using AngularJS? 如何使用AngularJS进行这项工作?

By $compile . 通过$compile Document here . 在这里记录

And an example, help it works. 举个例子,帮助它工作。

 angular.module('app', []) .controller('appCtrl', function($scope) { }) .directive('ngAddClass', function($compile) { return { restirct: 'AE', link: function(scope, ele, attrs) { scope.changeClass = function() { console.info('red'); return 'red'; } var target = angular.element(".nodeBranches"); for (var i = 0; i < target.length; i++) { target.eq(i).attr("ng-class", "changeClass()"); $compile(target)(scope); } } } }); 
 .red { color: red; } 
 <script src="//cdn.bootcss.com/jquery/2.0.0/jquery.js"></script> <script src="//cdn.bootcss.com/angular.js/1.4.7/angular.min.js"></script> <div ng-app="app"> <div ng-controller="appCtrl"> <div ng-add-class> <div class="node nodeBranches"> <p class=" node-name">TEXT</p> </div> </div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM