使用存储在控制器中的 id 变量过滤 ng-repeat 结果
Filter ng-repeat results using an id variable stored in controller
我的控制器中有一个 ID,比方说 id = 1
,还有一个数据项列表 $scope.items = data
。
数据结构如下所示:
"data": [ {
"id":1,
"name":"ranjith"
},
{
"id":2,
"name":"sumanth"
}
]
我的HTML
<span ng-repeat="item in items | filter: getResult">{{item.name}}</span>
getResult
在我的控制器中:
$scope.getResult = function(a){ if (a.id== $scope.id) return true; else return false; }
我只想输出id=1
的项,意思是id=1
和name=ranjith
的数据集。我尝试了一些代码,但似乎没有任何效果。
试试这个:
在html中:
<span ng-repeat="item in data | filter: getResult">{{item}}</span>
在控制器中:
$scope.data = [ { "id":1, "name":"ranjith" }, { "id":2, "name":"sumanth" } ];
$scope.id = 1;
//Filter
$scope.getResult = function(item){
return item.id == $scope.id;
};
您快要开始工作了,但是有几个错误:
- 您没有正确关闭
span
,
- 你没有在你的
span
中输出任何东西,所以即使它有效你也不会看到任何东西
- 您将数据集存储在名为
data
的 var 中,然后在 ng-repeat
中使用 items
您的代码至少应如下所示:
var app = angular.module("fiddle", []);
app.controller("fiddle_controller", function($scope){
$scope.items = [
{
"id":1,
"name":"ranjith"
},
{
"id":2,
"name":"sumanth"
}
];
$scope.id = 1;
$scope.getResult = function(item){
return item.id == $scope.id;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fiddle">
<div ng-controller="fiddle_controller">
<span ng-repeat="item in items | filter: getResult">
{{item.name}}
</span>
</div>
</div>
我的控制器中有一个 ID,比方说 id = 1
,还有一个数据项列表 $scope.items = data
。
数据结构如下所示:
"data": [ {
"id":1,
"name":"ranjith"
},
{
"id":2,
"name":"sumanth"
}
]
我的HTML
<span ng-repeat="item in items | filter: getResult">{{item.name}}</span>
getResult
在我的控制器中:
$scope.getResult = function(a){ if (a.id== $scope.id) return true; else return false; }
我只想输出id=1
的项,意思是id=1
和name=ranjith
的数据集。我尝试了一些代码,但似乎没有任何效果。
试试这个:
在html中:
<span ng-repeat="item in data | filter: getResult">{{item}}</span>
在控制器中:
$scope.data = [ { "id":1, "name":"ranjith" }, { "id":2, "name":"sumanth" } ];
$scope.id = 1;
//Filter
$scope.getResult = function(item){
return item.id == $scope.id;
};
您快要开始工作了,但是有几个错误:
- 您没有正确关闭
span
, - 你没有在你的
span
中输出任何东西,所以即使它有效你也不会看到任何东西 - 您将数据集存储在名为
data
的 var 中,然后在ng-repeat
中使用
items
您的代码至少应如下所示:
var app = angular.module("fiddle", []);
app.controller("fiddle_controller", function($scope){
$scope.items = [
{
"id":1,
"name":"ranjith"
},
{
"id":2,
"name":"sumanth"
}
];
$scope.id = 1;
$scope.getResult = function(item){
return item.id == $scope.id;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fiddle">
<div ng-controller="fiddle_controller">
<span ng-repeat="item in items | filter: getResult">
{{item.name}}
</span>
</div>
</div>