AngularJS$编译时使用第三方(jquery)



我正在一个当前使用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?有没有办法做到这一点?

我知道我应该加载数据,并尝试用angular来管理一切,但现在这是不可能的,否则我会打破所有旧东西。这就是为什么我要问这样一个问题。

注意:这是一个简单的例子,在我的实际情况中,我在加载的html中也有一些控制器和其他角度的东西。

我认为以您的方式使用angular不是一个好主意。

你可以这样做。使用$http或您自己的service加载数据。并通过=绑定指令的数据。

但是,我们可以使用$compile来实现您喜欢的:

$scope.loadContent = function () {
    var html = $compile("<my-directive></my-directive>")($scope);
    $("#target").append(html);
};

更多详细信息,请参阅http://jsfiddle.net/creeper/cyw9b2pk/

最新更新