我是AngularJS(和Web开发)的新手,但对双向绑定和ng-repeat
可能性感到非常兴奋。
我想构建一个类似于textfields结构的表格,我可以在列中添加更多字段,然后在右侧的列中添加字段。希望使用它来构建嵌套的JSON文件。
目前正在考虑这样的json
结构,但希望有一个更扁平的结构......
{
"NoClicks":
{ "C1": ["R1"],
"C2": ["R1"],
"C3": ["R1"]
},
"C1_R1_clicked":
{ "C1": ["R1", "R2"],
"C2": ["R1", "R2"],
"C3": ["R1", "R2"]
},
"C2_R1_clicked":
{ "C1": ["R1"],
"C2": ["R1", "R2"],
"C3": ["R1", "R2"]
}
,
"C3_R1_clicked":
{ "C1": ["R1"],
"C2": ["R1"],
"C3": ["R1", "R2"]
}
}
我试图回答我自己的问题并且非常接近目标..
但我会感谢任何答案(或我的答案的模式),让我归档目标。这当然将标记为问题的解决方案。
答案 0 :(得分:2)
将此stackoverflow问题Display nested list like a table与AngryCat's Amazing JSFiddle of nested nodes合并似乎让我走了一半
成为:JSFiddle
<强> HTML 强>
<script type="text/ng-template" id="my-tmpl">
{{data.name}}
<button class="btn" ng-click="add(data)" ng-show="levelLimit(data)">
Add node </button>
<button class="btn" ng-click="delete(data)" ng-show="hasNodes(data)">
Delete nodes </button>
<ul>
<li ng-repeat="data in data.nodes" ng-include="'my-tmpl'"></li>
</ul>
</script>
<ul ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'my-tmpl'"></li>
</ul>
<强> JS 强>
angular.module("myApp", [])
.controller("TreeController", function($scope) {
var levelLimit = function(data) {
if (data.level < 3) {
return true;
} else {
return false;
};
};
var addNode = function(data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
var newLevel = data.level + 1;
if (levelLimit(data)) {
var node = {
name: newName,
nodes: [],
level: newLevel
};
data.nodes.push(node);
addNode(node);
}
};
$scope.tree = [{
name: "Node",
nodes: [],
level: 1
}];
$scope.hasNodes = function(data) {
return (data.nodes.length > 0)
};
$scope.levelLimit = levelLimit;
$scope.delete = function(data) {
data.nodes = [];
};
$scope.add = addNode;
});
<强> CSS 强>
li {
display: inline-flex;
border: 1px solid #000;
padding: 0px;
list-style: none;
}
li li {
display:flex;
}
我只需要弄清楚3个部分
答案 1 :(得分:0)
由于列保存为对象属性,因此您需要对第一个ng-repeat
应用以下语法:
<div ng-repeat="(key, value) in myObj"> ... </div>
value
变量将包含您的列数组。您可以使用deault语法迭代数组。
答案 2 :(得分:0)
嗯,我是一个小小的&#39;困惑的设置,但听起来好像你想要一些功能作为递归指令?所以也许:
app.directive('jsonObjectView',[function(){
return {
restrict: 'E',
scope: {
jsonObjectView: '=' // two-way bind about the directive's name
},
template: '<div ng-repeat="(property,object) in JSONObjects"><div class="object-container"><json-object-view="object"></json-object-view><button ng-click="addProperty(object)"></button></div></div>', // the html template
compile: function (element,attributes){
// craft your "addProperty" function (not sure if you want a pop-up or how you're going about it)
return {
post: function postLink(scope,elem,attr,ctrl){
// Anything else you ought to do
}
};
}
};
}])
&#13;
<json-object-view="object"></json-object-view>
<!-- Which would equate to: -->
<div ng-repeat="(property,object) in JSONObjects">
<div class="object-container">
<json-object-view="object"></json-object-view>
<button ng-click="addProperty(object)"></button>
</div>
</div>
&#13;