Javascript ajax load()函数之后AngularJS将作用域绑定到html

Javascript ajax load()函数之后AngularJS将作用域绑定到html,javascript,jquery,angularjs,ajax,Javascript,Jquery,Angularjs,Ajax,读过之后,我了解到通过ajax加载的html并没有绑定到我的angular应用程序。我尝试了1000种方法,但无法让“customers invoice.html”理解。任何想法都将不胜感激 <body ng-cloak ng-app="myApp"> <main id="main"> <div ng-controller='Ctrl'> <a ng-click="openInvoice(data.invo

读过之后,我了解到通过ajax加载的html并没有绑定到我的angular应用程序。我尝试了1000种方法,但无法让“customers invoice.html”理解。任何想法都将不胜感激

<body ng-cloak ng-app="myApp">
    <main id="main">
        <div ng-controller='Ctrl'>
            <a ng-click="openInvoice(data.invoiceRef)" class="btn">View</a>
        </div>
    </div>
</body>


var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope, $compile) {
    $scope.invoice = {}
    $scope.openInvoice = function(ref) { 
        $scope.invoice.ref = ref;
        var html = $('#main');
        html.load('customers-invoice.html')
        $compile(html)($scope);          
    }
}

看法
var-app=angular.module('myApp',[]);
app.controller('Ctrl',函数($scope,$compile){
$scope.invoice={}
$scope.openInvoice=函数(ref){
$scope.invoice.ref=ref;
var html=$('#main');
load('customers-invoice.html')
$compile(html)($scope);
}
}

您可以使用
ng include
指令。在这种情况下,它将在指定的DOM中加载html,并为您准备好已编译的DOM绑定。但是,由于您希望获得
Ctrl
控制器的绑定,因此必须将该DOM放入
Ctrl
控制器
div

<body ng-cloak ng-app="myApp">
    <main id="main">
        <div ng-controller='Ctrl'>
            <a ng-click="openInvoice(data.invoiceRef)" class="btn">View</a>
            <div ng-include="templateUrl"></div>
        </div>

    </div>
</body>
您可以使用该服务将html文件加载到控制器,因为模板已加载到缓存中

 var app = angular.module('myApp', []);
 app.controller('Ctrl', function($scope, $compile, $templateRequest, $sce) {
     $scope.invoice = {}
     $scope.openInvoice = function(ref) {
         var templateUrl = $sce.getTrustedResourceUrl('customers-invoice.html');

         $templateRequest(templateUrl).then(function(template) {
             $compile($("#main").html(template).contents())($scope);
         });
     }
 })

我终于设法了解并改进了这个问题,并相应地解决了它。 因为我们执行的代码超出Angular的知识范围,所以我们需要编译插入的html以让它看到Angular,然后手动调用$scope.$digest()来更新标记

因此,这就是诀窍:

$compile($('idWhereIloadedContent').contents())($scope)


$scope.$digest();

我现在有了一个更好的解决方案!不要使用$.ajax,只需使用$http(我想它会在后台为您运行摘要循环)。总之,问题解决了

下面是angulajs页面的链接,解释如何使用$http
$http

谢谢,但仍然无法使修改后的作用域正常工作,请确保添加jquery库。我最终选择了此解决方案,因为它使用angular自己的方法。谢谢
 var app = angular.module('myApp', []);
 app.controller('Ctrl', function($scope, $compile, $templateRequest, $sce) {
     $scope.invoice = {}
     $scope.openInvoice = function(ref) {
         var templateUrl = $sce.getTrustedResourceUrl('customers-invoice.html');

         $templateRequest(templateUrl).then(function(template) {
             $compile($("#main").html(template).contents())($scope);
         });
     }
 })