Ale*_*lex 5 javascript json angularjs angularjs-directive
我想在 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)
};
});
Run Code Online (Sandbox Code Playgroud)
html看起来像
<div ng-repeat="(name, attributes) in fields">
<element name="{[{name}]}" attributes="{[{attributes}]}"></element>
</div>
Run Code Online (Sandbox Code Playgroud)
属性 json 对象的样子
{"name_displayed":"Agency","size":"30","tag":"input","type":"text"}
Run Code Online (Sandbox Code Playgroud)
一个名字看起来像
agency
Run Code Online (Sandbox Code Playgroud)
看起来我无法将函数用于模板,而且我似乎无法访问属性或名称对象。
看看这个: 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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
我假设“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>
Run Code Online (Sandbox Code Playgroud)
它有效,但是对于您试图解决的问题来说,这是一个非常糟糕的方法。
| 归档时间: |
|
| 查看次数: |
11820 次 |
| 最近记录: |