页面中有多个Ng-REPEAT

时间:2017-05-28 07:04:54

标签: jquery angularjs angularjs-ng-repeat angularjs-ng-click

我的index.html页面上有以下代码。

<button id="showdogs">Dogs</button>
<div ng-repeat="list in cats">
<li>{{list.name}}</li>
</div>

<script>
$scope.cats = [
        {name:"cat1"},{name:"cat2"},{name:"cat3"}]
$scope.dogs = [
        {name:"Dog1"},{name:"Dog2"},{name:"Dog3"}]
</script?

我想要展示

<div ng-repeat="dog in dogs">
<li>{{list.name}}</li>
</div>

按下#showdogs按钮时。 任何人都可以帮我使用AngularJs或Jquery吗?

2 个答案:

答案 0 :(得分:1)

您可以使用ng-click并在那里传递类型,并在控制器中根据类型填充数据源。

<button id="showdogs" ng-click="showItem('dog')">Dogs</button>

$scope.showItem = function(type){
   if(type === 'dog'){
      $scope.itemList = [{name:"Dog1"},{name:"Dog2"},{name:"Dog3"}];
   }
   else if(type === 'cat'){
      $scope.itemList = [{name:"cat1"},{name:"cat2"},{name:"cat3"}];
   }
};

在html中

<div ng-repeat="item in itemList">
   <li>{{item.name}}</li>
</div>

请参阅example plnkr

答案 1 :(得分:1)

<强> AngularJS:

您可以按如下方式使用ng-show并显示列表:

function Controller($scope) {
   $scope.displayCats = true;
   $scope.displayDogs = false;
    $scope.cats = [{name:"cat1"},{name:"cat2"},{name:"cat3"}];
		$scope.dogs = [{name:"Dog1"},{name:"Dog2"},{name:"Dog3"}];
    
    $scope.showDogs = function(){
    	$scope.displayDogs = true;
      $scope.displayCats = false;
    };
    
    $scope.showCats = function(){
    	$scope.displayDogs = false;
      $scope.displayCats = true;
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app ng-controller="Controller">
    <button id="showdogs"  ng-click="showDogs();">Dogs</button>
    <button id="showcats"  ng-click="showCats();">Cats</button>
    <div ng-show="displayCats" ng-repeat="list in cats">
    <li>{{list.name}}</li>
    </div>
    <div ng-show="displayDogs" ng-repeat="list in dogs">
    <li>{{list.name}}</li>
    </div>
</div>

<强> jQuery的:

var cats = [{name:"cat1"},{name:"cat2"},{name:"cat3"}];
var dogs = dogs = [{name:"Dog1"},{name:"Dog2"},{name:"Dog3"}];

$(document).ready(function(){
	$("#showdogs").click(function(){
   $(".listDiv > ul").empty();
  	$.each(dogs,function(ind){
      $(".listDiv > ul").append("<li>"+dogs[ind].name+"</li>");
    });
  });
  $("#showcats").click(function(){
  	$(".listDiv > ul").empty();
  	$.each(cats,function(ind){
      $(".listDiv > ul").append("<li>"+cats[ind].name+"</li>");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="showdogs">Dogs</button>
<button id="showcats">Cats</button>
<div class="listDiv">
<ul>

</ul>
</div>