【发布时间】:2013-09-14 12:30:11
【问题描述】:
是否可以在ng-repeat 中添加不同的 HTML 元素类型?
如果我有一个数组:
['line', 'arc', 'rectangle', 'line', 'polygon', ... ]
这些元素会有不同的 SVG 标签和不同的数据来定义它们。
是否可以让AngularJS根据值插入正确的标签?
【问题讨论】:
是否可以在ng-repeat 中添加不同的 HTML 元素类型?
如果我有一个数组:
['line', 'arc', 'rectangle', 'line', 'polygon', ... ]
这些元素会有不同的 SVG 标签和不同的数据来定义它们。
是否可以让AngularJS根据值插入正确的标签?
【问题讨论】:
我建议创建一个directive,它会在转发器的范围内通过,然后使用element.replaceWith 和$compile 来获取HTML。如果没有进一步的 Angular 绑定,您可以使用 $sce 输出受信任的 HTML。概率取决于站点所需的安全类型,我会亲自使用该指令。
** 我没有在下面测试过,我对 canvas/svg 的东西一无所知 :-)
页面上的html
<svg-object varObject="o" data-ng-repeat="o in varObjects"></svg-object>
控制器上的json模型
$scope.varObjects = [{ "shape": "circle", "id": "cir123", "cx": "50", "cy": "50", "r": "50", "fill": "red" }, { "shape": "rect", "id": "rec23", "width": "50", "height": "50", "fill": "green" }]
声明你的模块,命名它并将命名的模块包含在你的应用程序中
var module = angular.module('myApp.directives', [])
module.directive('svgObject', function ($compile) {
return {
scope:{ varObject:'@'
},
restrict: 'E',
link: function (scope, elem, attrs, ctrl) {
var rsltHtml = '<' + scope.varObject.shape
for (var property in scope.varObject) {
switch (property) { //properties to ignore
case "shape":
case "alsoignore":
continue;
}
if (scope.varObject.hasOwnProperty(property)) {
rsltHtml += ' '+ property + '="' + scope.varObject[property]+ '" ';
}
}
rsltHtml += "/>";
elem.replaceWith($compile(rsltHtml)(scope));
}
};
});
向主应用添加指令
var myApp = angular.module('myApp', ['myApp.directives', 'ngSanitize'])
【讨论】:
我对数组中的元素使用 ng-repeat 执行此操作,然后对值执行 ng-switch。
<li ng-repeat="q in context.array">
<div ng-switch on="q.type">
<div ng-switch-when="line">I AM A LINE</div>
<div ng-switch-when="arc">I AM AN ARC</div>
<div ng-switch-when="rectangle">I AM A RECTANGLE</div>
<div ng-switch-when="polygon">I AM A POLYGON</div>
</div>
</li>
【讨论】:
<div /> 将是一个问题,即使 show\hide 不是。我会报告发生的情况。