过滤数组并将过滤对象的属性用作

过滤数组并将过滤对象的属性用作

本文介绍了如何使用 AngularJS 过滤数组并将过滤对象的属性用作 ng-model 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象数组,并且我想根据过滤器将 Angular 模型绑定到其中一个元素的属性,我该怎么做?我可以用一个具体的例子更好地解释:

HTML:

<头><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script><元字符集=utf-8/><title>JS Bin</title><body ng-controller="MyCtrl"><输入 ng-model="results.year"><input ng-model="results.subjects.title | filter:{grade:'C'}"></html>

控制器:

function MyCtrl($scope) {$scope.results = {年份:2013,科目:[{title:'English',grade:'A'},{title:'Maths',grade:'A'},{title:'Science',grade:'B'},{title:'地理',等级:'C'}]};}

JSBin:http://jsbin.com/adisax/1/edit

我想将第二个输入过滤到等级为C"的主题,但我不想将模型绑定到等级;我想将它绑定到具有C"级的主题的标题.

这可能吗,如果有,是怎么做的?

解决方案

<input ng-model="subject.title"/>

If I have an array of objects, and I want to bind the Angular model to a property of one of the elements based on a filter, how do I do that? I can explain better with a concrete example:

HTML:

<!DOCTYPE html>
<html ng-app>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <meta charset=utf-8 />
        <title>JS Bin</title>
    </head>
    <body ng-controller="MyCtrl">
        <input ng-model="results.year">
        <input ng-model="results.subjects.title | filter:{grade:'C'}">
    </body>
</html>

Controller:

function MyCtrl($scope) {
  $scope.results = {
    year:2013,
    subjects:[
      {title:'English',grade:'A'},
      {title:'Maths',grade:'A'},
      {title:'Science',grade:'B'},
      {title:'Geography',grade:'C'}
    ]
  };
}

JSBin: http://jsbin.com/adisax/1/edit

I want to filter the second input to the subject with a grade 'C', but I don't want to bind the model to the grade; I want to bind it to the title of the subject that has grade 'C'.

Is this possible, and if so, how is it done?

解决方案
<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

这篇关于如何使用 AngularJS 过滤数组并将过滤对象的属性用作 ng-model 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:31