2013-10-11 88 views
0

我試圖加載html片段並在div標籤中顯示。在控制器帶有angularjs的動態html片段

<div my-rpt="report"> 
</div> 

現在我有::所以我寫了一個簡單的指令:

myDirectives.directive('myRpt', function() { 
    'use strict'; 
    return { 
     restrict: 'A', 
     scope: true, 
     link: function (scope, elem, attrs, ctrl) { 
      var htmlExpr = attrs.myRpt; 
      scope.$watch(htmlExpr, function (newHtml) { 
       if (newHtml) { 
        elem.html(newHtml); 
       } 
      }, false); 
     } 
    }; 
}); 

在HTML頁面中使用它像下面

$http.get('api/v1/general_ledger', { params: { q: { filter: [ 
    { 'name': 'begin_date', 'op': '==', 'val': $scope.criteria.beginDate }, 
    { 'name': 'end_date', 'op': '==', 'val': $scope.criteria.endDate }] 
}}}).then(
    function (resp) { 
     $scope.report = resp.data; 
    }, 
    function (resp) { 
     //TODO: show error message 
    } 
); 

上面的代碼工作,但我不確定這是否足夠好。例如,$ scope.report可能包含非常大的字符串/ html內容,但我猜瀏覽器將擁有自己的分析副本。另外,一般來說,創建業務報告的好方法是什麼,並在需要時生成pdf,excel文件等?

回答

0

由於元素內容是純粹的,服務器生成的HTML沒有動態綁定,我不明白爲什麼不使用這種方法。

如果HTML字符串足夠大,可以使用它,然後將其刪除以免佔用內存。刪除它可能需要稍微不同的代碼,例如使用事件並指定事件名稱作爲該指令的屬性:

// in the controller: 
$http.get(...).then(
    function(resp) { 
     $rootScope.broadcast("receivedReport", resp.data); 
    }, 
... 

// in the directive: 
link: function (scope, elem, attrs, ctrl) { 
    var eventName = attrs.myRpt; 
    scope.$on(eventName, function(data) { 
     elem.html(data); 
    }); 
} 

模板用法:

<div my-rpt="receivedReport"></div>