我会回应别人提到的内容:这种事情通常是一个坏主意,但我也明白,你有时不得不以不喜欢的方式使用旧代码.所有这一切,您可以将从Angular外部加载的HTML加载到
the $compile service的Angular-bound视图中.以下是您可以重写当前示例以使其与$compile一起工作的方式:
// We have to set up controllers ahead of time.
myApp.controller('AfterCtrl', function($scope) {
$scope.loaded = 'Is now loaded';
});
//loads html and afterwards creates a controller
$('button').on('click', function() {
$.get('ajax.html', function(data) {
// Get the $compile service from the app's injector
var injector = $('[ng-app]').injector();
var $compile = injector.get('$compile');
// Compile the HTML into a linking function...
var linkFn = $compile(data);
// ...and link it to the scope we're interested in.
// Here we'll use the $rootScope.
var $rootScope = injector.get('$rootScope');
var elem = linkFn($rootScope);
$('.content').append(elem);
// Now that the content has been compiled, linked,
// and added to the DOM, we must trigger a digest cycle
// on the scope we used in order to update bindings.
$rootScope.$digest();
}, 'html');
});
如果您可以将功能构建为指令而不是使用原始的jQuery,那么可以简化事情 – 您可以向其中注入$compile和$rootScope服务,甚至可以在指令中使用本地范围.如果您可以将动态绑定用于< ng-include>元素代替