我正在使用jquery加载东西的网站上实现angularjs。内容以异步方式加载,然后通过jquery而不是angularjs附加到DOM。所以我有这样的事情:
function loadContent () {
$("#target").html("<my-directive></my-directive>");
}
var app = angular.module("app", []);
app.directive("myDirective", function () {
return {
restrict: "E",
template: "my-directive is loaded"
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app">
<my-directive></my-directive>
<button onclick="loadContent()">load content</button>
<div id="target"></div>
</div>
所以我的问题是,是否可以通过jquery使用$compile
?有没有办法实现它?
我知道我应该加载数据并尝试用角度来管理所有内容但是现在它是不可能的,或者我将打破所有旧的东西。这就是我提出这样一个问题的原因。
注意:这是一个简单的例子,在我的实际案例中,我在加载的html中也有一些控制器和其他角度内容。
答案 0 :(得分:1)
我不认为在你的方式中使用棱角是个好主意。
你可以这样做。使用$http
或您自己的service
加载数据。并通过=
绑定您的指令数据。
但是,我们可以使用$compile
来实现您喜欢的目标:
$scope.loadContent = function () {
var html = $compile("<my-directive></my-directive>")($scope);
$("#target").append(html);
};
更多详细信息,请参阅http://jsfiddle.net/creeper/cyw9b2pk/