如何使用Spring MVC和Angular JS检索数据

时间:2018-11-30 08:37:31

标签: angularjs spring spring-mvc

控制器代码

@RequestMapping(value="/welcomes", method = RequestMethod.GET, produces="MediaType.application/json")
    public @ResponseBody ModelAndView welcome(@ModelAttribute UserBean userBean)
    {
        List<UserBean> usernames=new ArrayList<UserBean>();
        usernames = retrievedataservice.findAllUsers(userBean);
        System.out.println(usernames.size());
        return new ModelAndView("welcomes", "usernames", usernames);
    }

角度js代码

  <script>
    var app = angular.module('myApp', []);
    app.controller('UserController', ['$scope', '$http', function($scope, $http){
        $scope.reload = function () {
            $http({
                method : 'GET',
                url : 'welcomes'
            }).then(function successCallback(response){
                 $scope.usernames=response.data.usernames;
                 console.log("Success");
                 console.log($scope.usernames);
             },function errorCallback(response) {
                 $scope.err_state = true;
                 console.log(response.statusText);
             });
        };
             $scope.reload();

    }]);
    </script>
<div data-ng-app="myApp" data-ng-controller="UserController">
   <table border="1" width="50%" height="50%"> 
    <tr><th>user name</th><th>phone</th><th>email</th></tr>
     <tr data-ng-repeat="user in usernames">
     <td>{{user.username}}</td>
      <td>{{user.phone}}</td>
       <td>{{user.email}}</td>
       </tr>   
   </table>   

实际上,控制器返回数据列表,但是angular js无法获取数据。 console.log($ scope.usernames);返回空值。它不能与angular js和controller集成。

0 个答案:

没有答案