我想在angularjs中创建一个元素指令,该指令从作为属性传递的json blob生成html元素。我已经尝试了以下几种变化...
demoApp.directive("element", function() {
return {
restrict: "E",
scope: {
attributes: "@",
name: "@"
},
template:
function(name, attributes) {
var templateString = "<" + attributes.tag;
for (attribute in attributes) {
if (attribute != "name_displayed" && attribute != "tag") {
templateString += " " + attribute + "=\"" attributes[attribute] + "\"";
}
}
templateString += " name=\"" field + "\"";
templateString += ">";
templateString += "</" + attributes.tag + ">";
return attributes.name_displayed + ": " + templateString;
}(name, attributes)
};
});
的HTML看起来像
<div ng-repeat="(name, attributes) in fields">
<element name="{[{name}]}" attributes="{[{attributes}]}"></element>
</div>
其中属性json对象看起来像
{"name_displayed":"Agency","size":"30","tag":"input","type":"text"}
一个名字看起来像
agency
看来我无法为模板使用函数,也好像无法访问属性或名称对象。
检查一下:http : //jsfiddle.net/es4Y6/1/
var app = angular.module('hmm', []);
function ctrl($scope) {
$scope.fields = {
first: '{"name_displayed": "Agency", "size": "30", "tag": "input", "type": "text"}',
second: '{"name_displayed": "Foo", "size": "30", "tag": "input", "type": "password"}',
third: '{"name_displayed": "Bar", "size": "30", "tag": "input", "type": "number"}'
};
}
app.directive('blah', function() {
var template = function(name, attributes) {
var templateString = "<" + attributes.tag;
for (var attribute in attributes) {
if (attribute != "name_displayed" && attribute != "tag") {
templateString += " " + attribute + '="' + attributes[attribute] + '"';
}
}
templateString += ' name="' + name + '"';
templateString += ">";
templateString += "</" + attributes.tag + ">";
return attributes.name_displayed + ": " + templateString;
};
return {
restrict: "E",
link: function(scope, element, attrs){
var attributes = angular.fromJson(attrs.attributes);
var tpl = template(attrs.name, attributes);
element.html(tpl);
}
};
});
我假设“ json blob”是指json字符串。如果不是,那么您的意思是仅JS对象。在这种情况下,请更新$scope.fields
并删除angular.fromJson()
。
<div ng-app="hmm">
<div ng-controller="ctrl">
<div ng-repeat="(name, attributes) in fields">
<blah name="{{name}}" attributes="{{attributes}}"></blah>
</div>
</div>
</div>
它可以工作,但是对于您要解决的问题,这是一种非常糟糕的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句