我知道我可以申请模板/ templateURL,但目前内容将从我的应用程序的其他地方加载.
JSbin:http://jsbin.com/imuseb/1/
HTML
<html ng-app="app"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> </head> <body> <div alert>here</div> </body> </html>
JS代码:
var app = angular.module('app',[]); app.directive('alert',function (){ return { link: function (scope,element,attrs) { element.on("click",function (){ alert("here"); }); } }; }); $(function (){ $("body").append("<div alert>here too</div>"); });
解决方法
角度应用程序必须可以访问新DOM才能正确编译.这是一种方法(不是唯一的方法).要将新DOM应用于应用程序的$rootScope,请更改:
$(function (){ $("body").append("<div alert>here too</div>"); });
至:
app.run(function($rootScope){ $rootScope.$apply($("body").append("<div editable>here too</div>")); });
根据Angular docs:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events,setTimeout,XHR or third party libraries).