我有一个对象,里面有一个项目列表X,每个X都有一个Y列表,每个Y都有一个Z列表。
我想在点击按钮时隐藏跨度。我可以通过向每个对象和ng-click="obj.visible = !obj.visible"
添加“可见”属性来轻松实现。
但是这个解决方案意味着修改对象,我真的不想这样做。
有更好的解决方案吗?
我尝试使用track by或一种hashmap但没有取得真正的成功。 我是否应该修改模型并在以后需要保存时将其清除?
angular.module('myModule', []);
angular.module("myModule")
.controller("DemoCtrl", demoCtrl);
demoCtrl.$inject = ["$scope"];
//demoCtrl
function demoCtrl($scope) {
vm = this;
vm.xObjects = [
{ "xname" : "x1",
"Ys" : [{
"yname" : "y1",
"Zs" : [{ "zname" : "z1" },
{ "zname" : "z2" }]
},
{
"yname" : "y2",
"Zs" : [{ "zname" : "z3" },
{ "zname" : "z4" }]
}]
},
{ "xname" : "x2",
"Ys" : [{
"yname" : "y3",
"Zs" : [{ "zname" : "z5" },
{ "zname" : "z6" }]
},
{
"yname" : "y4",
"Zs" : [{ "zname" : "z7" },
{ "zname" : "z8" }]
}]
}
];
vm.addX = function(){
vm.xObjects.push({ "xname" : "foo", Ys : []});
}
vm.addY = function(x){
x.Ys.push({ "Yname" : "bar", Zs : []});
}
vm.addZ = function(y){
y.Zs.push({ "Zname" : "too"});
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body data-ng-app="myModule">
<div data-ng-controller="DemoCtrl as demoCtrl" >
<div data-ng-repeat="xobject in demoCtrl.xObjects">
<span data-ng-hide="">xobject.xname = {{xobject.xname}}</span>
<button data-ng-click="">collapse</button>
<div data-ng-repeat="yobject in xobject.Ys">
<span data-ng-hide="">- - -yobject.xname = {{yobject.yname}}</span>
<button data-ng-click="">collapse</button>
<div data-ng-repeat="zobject in yobject.Zs track by $index">
<span data-ng-hide="">- - -{{$index}}- - -zobject.xname = {{zobject.zname}}</span>
<button data-ng-click="">collapse</button>
</div>
- - - - - -<button data-ng-click="demoCtrl.addZ(yobject)">add Z </button>
</div>
- - -<button data-ng-click="demoCtrl.addY(xobject)">add Y </button>
</div>
<button data-ng-click="demoCtrl.addX()">add X </button>
</div>
</body>
</html>
答案 0 :(得分:0)
您可以通过在控制器范围中创建名为hidden
的属性来实现此目的。要隐藏嵌套元素,可以使用数组。
HTML:
<div ng-controller="DemoCtrl">
<div ng-repeat="x in xs">
<span ng-hide="hidden == $index">{{ x.name }}</span>
<button ng-click="hide($index)">Collapse</button>
<div ng-repeat="y in x.ys">
<span ng-hide="hidden == [x.$index, $index]">{{ y.name }}</span>
<button ng-click="hide([x.$index, $index])">Collapse</button>
<div ng-repeat="z in y.zs">
<span ng-hide="hidden == [x.$index, y.$index, $index]">{{ z.name }}</span>
<button ng-click="hide([x.$index, y.$index, $index])">Collapse</button>
</div>
</div>
</div>
</div>
使用此控制器:
angular.module("app", [])
.controller("DemoCtrl", function($scope) {
$scope.xs = [...]; // Your data here
$scope.hidden = -1; // Nothing hidden yet
$scope.hide = function(object) {
$scope.hidden = object;
};
});