What i am trying to do is simple. A user enters a value, on button click, my JS calls a service to retreive my JSON data and perform a search on the value entered against the JSON and if a match is found, display the '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');
});
}
}
});
My 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"
}
]
}
}
Here's my fiddle: http://jsfiddle.net/oampz/7bB6A/
I am able to call my service, and retrieve the data from the JSON, but i am stuck on how to perform a search on my retrieved data against the value entered.
Thanks
UPDATE:
The following finds a serialnumber entered:
angular.forEach($scope.MyData, function(value, key) {
if (key === enteredValue) {
console.log("I Found something...");
console.log("Serial: " + key);
console.log("Owner: " + key.Owner);
}
})
I can display the found serialNumber via console.log("Serial: " + key);
but trying to display the Owner as console.log("Owner: " + key.Owner);
is showing as Undefined.