2017-09-13 35 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();