动态地重新编译角度指令 [英] re-compile angular directives dynamically

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

问题描述

http://jsfiddle.net/RW46a/2/

<div ng-app='myApp' ng-controller='MyController'>
    <button id="addbtn">add dynamic content</button>
    <div id="mycontent">
        <button ng-click='click()'>click here</button><br/>
        <!-- another button will be added here but its ng-click won't work -->
    </div>
</div>

我的应用程序使用一个外部的依赖,与jQuery的添加HTML code直接到DOM(叹息的)pretty作为小提琴描绘了。

My app uses an external dependency that with jQuery adds HTML code directly to the DOM (sigh) pretty much as depicted in the fiddle.

我希望能够angularize一些动态添加code,例如添加一个NG-点击指令到一个新的按钮的附加在为myContent分区见上发表评论。什么是角友好的方式来做到这一点的最好方法是什么?我试着使用$编译但很快就哈克。

I would like to be able to angularize some of the dynamically added code, e.g. add an ng-click directive to a new button that's appended to the "mycontent" div, see comment above. What is the best way to do this in an angular friendly way? I tried to make use of $compile but that quickly got hacky.

谢谢!

推荐答案

这拨弄显示的一个很多方法可以实现你想什么。现在,我不是说这是你的情况是正确的。但是,没有更多的信息很难知道你正在努力实现的是什么。

This fiddle shows one of many ways to achieve what you are trying. Now, I'm not saying this is correct for your situation. However, without more information it is hard to know exactly what you are trying to achieve.

有经常的方式来实现与角度动态DOM操作不具有使用 $编译做的。我希望我已经给你一个想法。

There is often ways to achieve 'dynamic' DOM manipulation with angular that does not have to do with using $compile. I hope I've given you one idea.

基本上,你可以使用 NG-节目的第一个元素,然后 NG-重复为休息:

Basically, you can use ng-show for the first element and then ng-repeat for the rest:

JS:

var app = angular.module('myApp', []);

function MyController($scope) {
  $scope.click = function() {
    alert('Clicked');
  };

    $scope.add = function() {
       $scope.contentCollection.push(1);
    }

  $scope.contentCollection = [];
}

HTML:

<div ng-app='myApp' ng-controller='MyController'>
    <button ng-click="add()" id="addbtn">add dynamic content</button>
    <div ng-show="contentCollection.length > 0" ng-repeat="content in contentCollection">
        <button ng-click='click()'>click here</button><br/>
    </div>
</div>

这篇关于动态地重新编译角度指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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