我在AngularJS控制器這樣的數組:如何根據給定的信息找到一個數組對象?
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
我有一個名爲「露西」,我怎麼能得到這個名字的年齡在控制器(未在HTML)?
我在AngularJS控制器這樣的數組:如何根據給定的信息找到一個數組對象?
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
我有一個名爲「露西」,我怎麼能得到這個名字的年齡在控制器(未在HTML)?
我在這裏創建了一個簡單的結果,只是年齡,以及多個結果。
這也可以一個過濾器,這是在這裏的角部位文件內實施:https://docs.angularjs.org/api/ng/filter/filter
https://plnkr.co/edit/OFRMzpQrZfTOnaFyJP7Z?p=info
angular.module('plnk',[]).controller('plnkCtrl', function($scope){
// Note, I added a second Joey here to test the multiple function.
// For output, check the browser console.
$scope.persons = [{name:'Joey', age:'27'},{name:'Joey', age:'28'},{name:'Lucy', age:'22'}]
console.log('Single -> ', getAgeSingle('Lucy'));
console.log('Multiple ->',getAgeMultiple('Joey'));
function getAgeMultiple(personLookup) {
var results = [];
angular.forEach($scope.persons,function(person){
if (person.name === personLookup) {
results.push(person);
// or results.push(person.age) for age only
}
});
return results;
}
function getAgeSingle(personLookup) {
var result = '';
angular.forEach($scope.persons,function(person){
if (person.name === personLookup && !result) {
result = person.age;
}
});
return result;
}
});
如果通過範圍要循環:
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}]
function getAge(name) {
angular.forEach($scope.persons, function (value, index) {
if (value.name === name) {
return parseInt(value.age, 10);
}
});
return undefined;
}
的HTML方式:
<div ng-app="myApp" ng-controller="MainCtrl">
<table>
<tr ng-repeat="person in persons">
<td>Name: {{person.name}} Age: {{person.age}}</td>
</tr>
</table>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}];
});
這並不做任何過濾按OP問題。 OP還表示,他們想要在控制器中檢索..非HTML – charlietfl
@charlietfl更新以包括過濾器。 – fuzz
只是循環陣列上,並檢查,這樣:
function getAge(name)
{
for (var i = 0; i < $scope.persons.length; i++)
{
var person = $scope.persons[i];
if (person.name === name)
{
return parseInt(person.age, 10);
}
}
return undefined;
}
這有幾個警告 - 如果你有欺騙,你只會得到第一個,它會在線性時間運行。如果你控制數據源,最好使用JS對象/ hashmap/dictionary /無論你想調用它。
我喜歡這個,因爲它佔多個同名的人。 – fuzz