2017-09-13 90 views
1

在阅读了解它之后,我了解到通过ajax加载的html不绑定到我的角度应用程序。我已经尝试过1000次,但无法获得'customers-invoice.html'来理解角度。任何想法将不胜感激。AngularJS将范围绑定到html后ajax加载()函数

<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);   
    } 
} 

回答

1

你可以在这种情况下使用ng-include指令,它会做负荷的html在指定的DOM编译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> 

代码

$scope.openInvoice = function(ref) { 
    $scope.invoice.ref = ref; 
    $scope.templateUrl = 'customers-invoice.html';  
} 
+0

我终于选择了这个解决方案,因为它使用了自己的方法。谢谢 – ClaraG

1

可以使用$templateCache服务加载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); 
     }); 
    } 
}) 
+0

谢谢,但仍然无法渲染修改范围 – ClaraG

+0

其工作,请务必添加jquery lib。 https://plnkr.co/edit/bpBXDi7PC7gYBOgz3h0Y?p=preview –

+0

是的!谢谢 – ClaraG

0

我终于找到了更好的问题并相应地解决了问题。 因为我们正在执行Angular的知识以外的代码,所以我们需要编译插入的html来查看Angular,然后手动调用$ scope。$ digest()来更新标记。

因此,这只是做的伎俩:

$编译($( '#idWhereIloadedContent')的内容()。)($范围);

$ scope。$ digest();