ng-repeat与不同的元素类型

时间:2013-09-10 17:06:52

标签: html5 angularjs svg

是否可以在ng-repeat

中添加不同的HTML元素类型

如果我有一个数组:

['line', 'arc', 'rectangle', 'line', 'polygon', ... ]

这些元素将有不同的SVG标记和不同的数据来定义它们。

是否可以让AngularJS根据值插入正确的标签?

2 个答案:

答案 0 :(得分:2)

我建议制作一个directive,它将在转发器的范围内过去,然后执行element.replaceWith$compile来获取HTML。如果没有进一步绑定angular,您可以使用$sce输出可信HTML。 Prob取决于网站上所需的安全类型,我会亲自使用该指令。 **我没有在下面测试过,我对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']) 

答案 1 :(得分:1)

我使用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>
相关问题