Angular Search for value in JSON and display corresponding data

后端 未结 1 707
挽巷
挽巷 2021-01-31 06:39

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 JS

相关标签:
1条回答
  • 2021-01-31 07:18

    The key is just to iterate over the data object while observing the correct structure for accessing the values.

    Your search function could look like this:

    $scope.results = [];
    $scope.findValue = function(enteredValue) {     
        angular.forEach($scope.myData.SerialNumbers, function(value, key) {
            if (key === enteredValue) {
                $scope.results.push({serial: key, owner: value[0].Owner});
            }
        });
    };
    

    Notice that I'm pushing the results into an array. You can setup an ng-repeat in the view which will use this to present a live view of the results:

    <input type="text" ng-model="enteredValue">
    <br>
    <button type="button" ng-Click="findValue(enteredValue)">Search</button>
    <h3>Results</h3>
    <ul>
        <li ng-repeat="result in results">Serial number: {{result.serial}}
        | Owner: {{result.owner}}</li>
    </ul>
    

    Demo

    0 讨论(0)
提交回复
热议问题