我试图做的事情很简单。用户输入一个值,点击按钮后,我的JS调用一个服务来检索我的JSON数据,并根据输入的值对JSON执行搜索,如果找到匹配项,则显示“Owner”。
HTML:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<input type="text" ng-model="enteredValue">
</br>
<button type="button" ng-Click="findValue(enteredValue)">Search</button>
</div>
</div>
JS:
angular.module('myApp', []).controller('MainCtrl', function ($scope, $http, getDataService) {
$scope.findValue = function(enteredValue) {
alert("Searching for = " + enteredValue);
$scope.MyData = [];
getDataService.getData(function(data) {
$scope.MyData = data.SerialNumbers;
});
}
});
angular.module('myApp', []).factory('getDataService', function($http) {
return {
getData: function(done) {
$http.get('/route-to-data.json')
.success(function(data) {
done(data);
})
.error(function(error) {
alert('An error occured');
});
}
}
});
我的 JSON:
{
"SerialNumbers": {
"451651": [
{
"Owner": "Mr Happy"
}
],
"5464565": [
{
"Owner": "Mr Red"
}
],
"45165": [
{
"Owner": "Mr Sad"
}
],
"4692": [
{
"Owner": "Mr Green"
}
],
"541": [
{
"Owner": "Mr Blue"
}
],
"D4554160N": [
{
"Owner": "Mr Loud"
}
]
}
}
这是我的代码示例:http://jsfiddle.net/oampz/7bB6A/
我可以调用我的服务并从JSON中检索数据,但我不知道如何对检索到的数据执行根据输入值进行搜索的操作。
谢谢。
更新:
以下代码可查找输入的序列号:
angular.forEach($scope.MyData, function(value, key) {
if (key === enteredValue) {
console.log("I Found something...");
console.log("Serial: " + key);
console.log("Owner: " + key.Owner);
}
})
我可以通过 console.log("Serial: " + key);
显示找到的序列号,但尝试显示所有者时,console.log("Owner: " + key.Owner);
显示为 未定义。
console.log("Owner: " + key[0].Owner)
。 - Marc Klineconsole.log("Owner: " + value[0].Owner);
:演示。 - Marc Kline