Angular 不知道您在 jQuery 中所做的更改。您需要通过 Angular 加载 html 并调用编译服务:
$compile(HTML)($scope);
或者发出事件并告诉 Angular 编译它。前几天我刚刚回答了一个类似的问题,关于如何让 Angular 了解通过 jquery 所做的更改:AngularJS legacy integration and content that contains asynchronously changing id doesn't trigger watcher
要清理,您需要将 ngSanitize 模块添加到您的项目中。但我相信你可以使用 $sce 服务告诉 Angular,如果你信任它就不要打扰它
即
<div id="mainDiv" compile-directive></div>
$().ready(function () {
$.get('pages/home.html', function(data){
$(document).trigger('customEvent', [data]);
});
});
angular.module('test').run(['$rootScope', function ($rootScope) {
//capture jQuery events and re-broadcast them as angular events
//events to capture
var events = [
'customEvent'
];
//To Use: $scope.$on('eventName', function(ngEvent, jqEvent, data)
$(document).on(events.join(' '), function(e) {
$rootScope.$broadcast.apply($rootScope, [e.type].concat(Array.prototype.slice.call(arguments, 0)));
});
});
angular.module('test').directive('compileDirective', function($compile, $sce){
return{
restrict: 'AE',
link: function(scope, element, attrs){
scope.$on('customEvent', function(ngEvent, jqEvent, data){
scope.$apply(function(){
angular.element.append($compile($sce.trustAsHtml(data))(scope));
});
};
}
};
});