带有angularjs的动态html片段
我正在尝试加载html片段并显示内部div标记。所以我写了一个简单的指令:带有angularjs的动态html片段,angularjs,pdf-generation,reporting,angularjs-directive,Angularjs,Pdf Generation,Reporting,Angularjs Directive,我正在尝试加载html片段并显示内部div标记。所以我写了一个简单的指令: myDirectives.directive('myRpt', function () { 'use strict'; return { restrict: 'A', scope: true, link: function (scope, elem, attrs, ctrl) { var htmlExpr = attrs.myRpt;
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);
}
};
});
// 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);
});
}
在html页面中,它的使用方式如下:
<div my-rpt="report">
</div>
上面的代码是有效的,但我不确定它是否足够好。例如,$scope.report可能包含非常大的字符串/html内容,但我猜浏览器将有自己的解析副本。另外,一般来说,编写业务报告的好方法是什么,以及在需要时生成pdf、excel文件等 由于元素内容是简单的、服务器生成的HTML,没有动态绑定,我不明白为什么不使用这种方法 如果HTML字符串足够大,您可以使用它,然后删除它,以免占用内存。删除它可能需要稍微不同的代码,例如使用事件并将事件名称指定为指令的属性:
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);
}
};
});
// 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>
由于元素内容是简单的、服务器生成的HTML,没有动态绑定,我不明白为什么不使用这种方法 如果HTML字符串足够大,您可以使用它,然后删除它,以免占用内存。删除它可能需要稍微不同的代码,例如使用事件并将事件名称指定为指令的属性:
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);
}
};
});
// 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>
无需创建自己的指令,因为您可以使用 或
无需创建自己的指令,因为您可以使用 或