javascript - 在 AngularJS 中通过表单传递过滤器?

标签 javascript angularjs

我正在尝试自学 AngularJS,我已经盯着这段代码看了这么久,我的眼睛都开始交叉了。

我有一个 JSON 文件 cats包含属性 name , sex , color , pattern ,和picture对于每个 cat目的。 (sex 在本例中是一个 bool 值;0 代表女性,1 代表男性。这很快就会恢复。)

我使用以下代码循环遍历 JSON 文件并打印出所有 cat 的表格对象,并且它工作正常(甚至稍微美化了格式):

<table>
  <tr>
    <th>Name</th>
    <th>Sex</th>
    <th>Color</th>
    <th>Pattern</th>
    <th>Picture</th>
  </tr>
  <tr ng-repeat="kitty in cats">
    <td>{{kitty.name|capitalize}}</td>
    <td ng-if="kitty.sex == 0">Female</td>
    <td ng-if="kitty.sex == 1">Male</td>
    <td>{{kitty.color|capitalize}}</td>
    <td>{{kitty.pattern|capitalize}}</td>
    <td ng-if="kitty.picture"><img ng-src="{{kitty.picture}}" alt="{{kitty.name|capitalize}}"></td>
    <td ng-if="!kitty.picture">NO IMAGE</td>
  </tr>
</table>

我现在想要的是允许用户单击复选框,例如“男性”,并更改 View 以显示全部 cat对象在 sex1 。我可以通过替换来实现这一点:

<tr ng-repeat="kitty in cats">

...与...

<tr ng-repeat="kitty in cats | filter:{'sex': 1}">

...但出于显而易见的原因,我更希望动态提供此功能,而不是硬编码。

我已经尝试了各种 ng-models 以及给定复选框上的名称、ID 和值,但我尚未找出传递参数 1 的正确语法。到重复功能,让它根据需要过滤猫。

有人对如何绑定(bind)这两者有任何想法吗?

最佳答案

你可能想要这个: HTML

<table>
  <tr>
    <th>Name</th>
    <th>Sex</th>
    <th>Color</th>
    <th>Pattern</th>
    <th>Picture</th>
  </tr>
  <tr ng-repeat="kitty in cats | filter : {sex: genderFilter}">
    <td>{{ kitty.name }}</td>
    <td>{{ kitty.sex ? 'Male' : 'Female' }}</td>
    <td>{{ kitty.color }}</td>
    <td>{{ kitty.pattern }}</td>
    <td ng-if="kitty.picture">
      <img ng-src="{{kitty.picture}}" alt="{{kitty.name|capitalize}}">
    </td>
    <td ng-if="!kitty.picture">NO IMAGE</td>
  </tr>
</table>

<label>
  <input type="checkbox" 
         ng-true-value="1" 
         ng-false-value 
         ng-model="genderFilter">Male
</label><br>
<label>
  <input type="checkbox" 
         ng-true-value="0" 
         ng-false-value 
         ng-model="genderFilter">Female
</label>

骗子:http://plnkr.co/edit/av2cyzJmwxJLkqhSFnOv?p=preview

关于javascript - 在 AngularJS 中通过表单传递过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40410921/

相关文章:

javascript - 访问嵌套指令内的父范围变量

javascript - 如何在d3.js中选择当前元素的父元素

javascript - AngularJs:ng-if react 太迟

javascript - jQuery click 与 AngularJS ng-click 结合使用不触发

javascript - 将 JS 引擎嵌入到 Windows Phone 应用程序中

angularjs - 以 AngularJS 路由结尾的奇怪 URL

javascript - AngularJS 使用 $rootScope 作为数据存储

JavaScript 返回值第 2 部分

javascript - 文档就绪时调用函数

javascript - 使用 jQuery 或 JavaScript 使用另一个数组过滤数组