10

我想做的很简单。用户输入一个值,单击按钮时,我的 JS 调用一个服务来检索我的 JSON 数据并针对 JSON 输入的值执行搜索,如果找到匹配项,则显示“所有者”。

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);但尝试将 Ownerconsole.log("Owner: " + key.Owner);显示为Undefined

4

1 回答 1

10

关键是在观察访问值的正确结构的同时迭代数据对象。

您的搜索功能可能如下所示:

$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});
        }
    });
};

请注意,我将结果推送到数组中。您可以在视图中设置 ng-repeat,它将使用它来呈现结果的实时视图:

<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>

演示

于 2014-06-06T14:39:15.777 回答