记录生活中的点滴,分享、学习、创新
学习ng-repeat的过程中常常使用到ng-repeat=”item in array”来循环输出所需要的元素,但是当我们需要使用ng-repeat进行多层嵌套时则容易出现数据重复的问题。
如在加载与点击事件于js中进行两次http请求获取data分别为list01[]数组和list02[]赋值再如下显示则会导致it1下每个ul都会重复输出list02[]数组中的内容
1 2 3 4 5 6  | <ul ng-repeat="it1 in list01">  <li ng-click="show(it1)">{{it1.value}}</li>  <ul ng-repeat="it2 in list02">    <li>{{it2.value}}</li>  </ul></ul> | 
输出如:
1 2 3 4  | 1-11-21-11-2 | 
而非
1 2 3 4  | 1-11-22-12-2 | 
其实这个也不是问题,只要换一种思维方式将列表和父级元素相关联形成树状结构就好了
HTML中代码如下
1 2 3 4 5 6 7 8 9 10 11 12  | <ul ng-repeat="it1 in list01">  <li ng-click="show(it1)">{{it1.name}}</li>  <ul ng-repeat="it2 in it1.child" ng-show="it1.showChild" style="text-indent:10px;">    <li ng-click="show(it1, it2)">{{it2.name}}</li>    <ul ng-repeat="it3 in it2.child" ng-show="it2.showChild" style="text-indent:10px;">      <li ng-click="show(it1, it2, it3)">{{it3.name}}</li>      <ul ng-repeat="it4 in it3.child" ng-show="it3.showChild">        <li>{{it4.name}}</li>      </ul>    </ul>  </ul></ul> | 
js中代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  | $http.get('ng01.json').success(function (_data) {  $scope.list01 = [];  $scope.list01 = _data.data;});$scope.show = function (it1, it2, it3) {  if(it3 != null){    $http.get("ng04.json").success(function (_data) {      $scope.list04 = [];      $scope.list04 = _data.data;      for(var x in $scope.list03){        $scope.list03[x].showChild = false;      }      it3.showChild = true;      it3.child = _data.data;     });     return;  }  if(it2 != null){    $http.get("ng03.json").success(function (_data) {      $scope.list03 = [];      $scope.list03 = _data.data;      for(var x in $scope.list02){        $scope.list02[x].showChild = false;      }      it2.showChild = true;      it2.child = _data.data;    });    return;  }  $http.get("ng02.json").success(function (_data) {    $scope.list02 = [];    $scope.list02 = _data.data;    for(var x in $scope.list01){      $scope.list01[x].showChild = false;    }    it1.showChild = true;    it1.child = _data.data;  });} | 
json文件都是这样的
1 2 3 4 5 6 7  | { "success":1, "data":[  {"name":"01"},  {"name":"02"} ]} |