有没有办法使用Angular来显示按钮上的内容?

Al-*_*-76 3 javascript arrays angularjs

我想在我的页面上显示文章列表.首先显示所有内容,但如果用户单击按钮,则只显示与单击按钮相关的文章.这意味着它将查看阵列中的"葡萄",如果是红色,则显示列表中的红葡萄酒.最好有一个按钮来显示所有默认返回初始视图的按钮.欢迎任何帮助.

<button>Show ALL Articles<button>
<button ng-click="filter('red')">Show me articles with red wines<button>
<button ng-click="filter('white')">Show me articles with white wines<button>
<button ng-click="filter('rose')">Show me articles with rose wines<button>

<ul>
    <li ng-repeat="item in wineListings | filter: filter">
        <h2>{{item.country}}</h2>
        <p>{{item.grape}}</p>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)
$scope.wineListings = [
    {
        country:"France",
        grape:"red"
    },
    {
        country:"Spain",
        grape:"red"
    },
    {
        country:"Italy",
        grape:"white"
    },    
    {
        country:"USA",
        grape:"rose"
    }
];
Run Code Online (Sandbox Code Playgroud)

Aln*_*tak 5

您可以通过在作用域中添加一个附加变量来实现所需,只需| filter通过Angular的内置对象匹配语法作为参数传递,具体如下:

wineListings | filter: { grape: selected }
Run Code Online (Sandbox Code Playgroud)

var app = angular.module('testApp',[])

app.controller('testCtrl',function($scope) {
$scope.wineListings = [
    {
        country:"France",
        grape:"red"
    },
    {
        country:"Spain",
        grape:"red"
    },
    {
        country:"Italy",
        grape:"white"
    },    
    {
        country:"USA",
        grape:"rose"
    }
];
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<button ng-click="selected=''">Show me all wines</button>
<button ng-click="selected='red'">Show me red wines</button>
<button ng-click="selected='white'">Show me white wines</button>
<button ng-click="selected='rose'">Show me rose wines</button>

<ul>
    <li ng-repeat="item in wineListings | filter : { grape: selected }">
        <h2>{{item.country}}</h2>
        <p>{{item.grape}}</p>
    </li>
</ul>
</body>
Run Code Online (Sandbox Code Playgroud)

  • @ Al-76你不必发布另一个我想回答的答案 (2认同)