如何使用Angularjs从JSON获取数据?

时间:2022-09-25 23:34:31

var app = angular.module("app", []);

app.controller('emp', ['$scope', 'empService', function($scope, empService){
    $scope.doSearch = function(){
        empService.findEmployeeById($scope.searchempno, function(r){
            $scope.empno = r.empno;
            $scope.ename = r.ename;
            $scope.salary = r.salary;
            $scope.dptno = r.dptno;
        });
    };
}]);

app.service('empService', ['$http', '$log', function($http, $log){
    this.findEmployeeById = function(empno, cb){
        $http({
            url: 'employees.json' + empno,
            method: 'GET'
        }).then(function(resp){
            cb(resp.data);
        });
    };
}]);
<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body ng-app="app">
        <div ng-controller="emp">
            <form class="form-inline">
                <div class="form-group">
                    <label>Enter Employee Number:</label>
                    <input type="text" class="form-control" ng-model="searchEmpno"/>
                </div>
                <button class="btn btn-primary" ng-click="doSearch()">Search</button>
            </form>
            <hr>
            <div class="row">
                <div class="col-sm-2">Employee No</div>
                <div class="col-sm-2">{{empno}}</div>
            </div>
            <div class="row">
                <div class="col-sm-2">Employee Name</div>
                <div class="col-sm-2">{{ename}}</div>
            </div>
            <div class="row">
                <div class="col-sm-2">Salary</div>
                <div class="col-sm-2">{{salary}}</div>
            </div>
            <div class="row">
                <div class="col-sm-2">Deptno</div>
                <div class="col-sm-2">{{dptno}}</div>
            </div>
        </div>
    </body>
</html>

If I gave the number in input field like 1001 and click the search button. It will not show the details. I have checked the console, there is no error. My JSON file has been placed the same location of the HTML file.

如果我在输入框中输入数字,比如1001,然后单击search按钮。它不会显示细节。我检查了控制台,没有错误。我的JSON文件被放置在HTML文件的相同位置。

Thanks, SamBhishma

谢谢,SamBhishma

2 个解决方案

#1


1  

I have created an updated plunker here. First issue was what I mentioned in the comment. In your view, you are writing <input type="text" class="form-control" ng-model="searchEmpno"/>and in your controller, you're trying to access this variable as searchempno

我在这里创建了一个更新的柱塞。第一个问题是我在评论中提到的。在您的视图中,您正在编写,在您的控制器中,您试图以searchEmpno的形式访问该变量

Second issue is in your http request. You cannot pick and choose the data from json file based on the id. You have to get the entire JSON file, parse it and filter out the value if it matches your searchEmpno model value. I fixed it in the plunker.

第二个问题出现在http请求中。您不能根据id来选择和选择json文件中的数据,您必须获得整个json文件,解析它并过滤掉它的值,如果它与您的searchEmpno模型值匹配的话。我把它固定在活塞上。

Third issue, you are attaching plain values to your scope like $scope.empno , $scope.ename. Instead, you need to put such values into an object, so in your controller, put the matched employee object in the scope and in your view, reference it as {{obj.ename}} and so on.

第三个问题,您正在将普通值附加到范围中,比如$scope。empno,scope.ename美元。相反,您需要将这些值放入对象中,因此在您的控制器中,将匹配的employee对象放入范围中,并在您的视图中,将其引用为{{obj]。ename } }等等。

Another thing, no need to return callbacks inside then. The clean way of handling successful, failed http calls is:

另外,不需要返回回调。处理成功失败的http调用的干净方法是:

$http.get('url').then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

Read more about them here.

在这里阅读更多关于它们的信息。

Take a look at the updated plunker to see if it matches your needs.

看看更新后的柱塞是否符合你的需要。

#2


0  

Problem is your model variable is wrong inside the view, try this

问题是你的模型变量在视图中是错误的,试试这个

<input type="text" class="form-control" ng-model="searchEmpno"/>

DEMO

演示

#1


1  

I have created an updated plunker here. First issue was what I mentioned in the comment. In your view, you are writing <input type="text" class="form-control" ng-model="searchEmpno"/>and in your controller, you're trying to access this variable as searchempno

我在这里创建了一个更新的柱塞。第一个问题是我在评论中提到的。在您的视图中,您正在编写,在您的控制器中,您试图以searchEmpno的形式访问该变量

Second issue is in your http request. You cannot pick and choose the data from json file based on the id. You have to get the entire JSON file, parse it and filter out the value if it matches your searchEmpno model value. I fixed it in the plunker.

第二个问题出现在http请求中。您不能根据id来选择和选择json文件中的数据,您必须获得整个json文件,解析它并过滤掉它的值,如果它与您的searchEmpno模型值匹配的话。我把它固定在活塞上。

Third issue, you are attaching plain values to your scope like $scope.empno , $scope.ename. Instead, you need to put such values into an object, so in your controller, put the matched employee object in the scope and in your view, reference it as {{obj.ename}} and so on.

第三个问题,您正在将普通值附加到范围中,比如$scope。empno,scope.ename美元。相反,您需要将这些值放入对象中,因此在您的控制器中,将匹配的employee对象放入范围中,并在您的视图中,将其引用为{{obj]。ename } }等等。

Another thing, no need to return callbacks inside then. The clean way of handling successful, failed http calls is:

另外,不需要返回回调。处理成功失败的http调用的干净方法是:

$http.get('url').then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

Read more about them here.

在这里阅读更多关于它们的信息。

Take a look at the updated plunker to see if it matches your needs.

看看更新后的柱塞是否符合你的需要。

#2


0  

Problem is your model variable is wrong inside the view, try this

问题是你的模型变量在视图中是错误的,试试这个

<input type="text" class="form-control" ng-model="searchEmpno"/>

DEMO

演示