【问题标题】:AngularJS $compile while using third party (jquery)AngularJS $compile 同时使用第三方(jquery)
【发布时间】:2014-11-10 09:42:21
【问题描述】:

我正在使用 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 中还有一些控制器和其他有角度的东西。

【问题讨论】:

    标签: jquery ajax angularjs


    【解决方案1】:

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

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

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

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

    更多详情见http://jsfiddle.net/creeper/cyw9b2pk/

    【讨论】:

    • 是的,我很遗憾我不得不做这样的事情,但是整个网站都是建立在 jquery 之上的,我现在不能破坏一切。
    猜你喜欢
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多