如何使用AngularJS与SpringMVC异步加载数据?

时间:2013-03-01 11:47:29

标签: javascript jquery spring spring-mvc angularjs

我是AngularJS的新手,对于解决以下情况的最佳方法感到疑惑:

1。我需要显示过去30天的数据行。 (默认选项)

我是怎么做的:当页面加载时,Spring控制器将列表放在模型属性中。

@RequestMapping(value="/show/data", method = RequestMethod.GET)
    public String getDataPage(ModelMap model) {
        //cropped for brevity
        List<Data> dataList = dataService.getData(fromDate, toDate);
        model.addAttribute("dataList ", dataList );

        return "data-page";
    }

在JSP中我使用EL标签循环遍历List并以表格形式向用户显示数据

<c:forEach var="currentData" items="${dataList}">
    <tr>
        <td>${currentData.name}</td>
        <td>${currentData.address}</td>
        <td>${currentData.email}</td>
        <td>${currentData.phone}</td>
    </tr>
</c:forEach>
  1. 用户可以选择日期范围&amp;根据所选范围(例如今天,昨天,上周,上个月,自定义范围),显示的数据应更新。
  2. 我是怎么做的:我正在使用Bootstrap-Daterangepicker(https://github.com/dangrossman/bootstrap-daterangepicker)来显示标记。它为我提供了一个回调函数。

    $('#reportrange').daterangepicker(options, callback);
    

    e.g。 $('#reportrange').daterangepicker(options, function(startDate, endDate){});

    如果没有AngularJS,这将是混乱的。 我可以调用jQuery ajax然后获取一个列表,然后在jQuery中搞乱DOM元素。但这很麻烦。

    如何在此场景中包含AngularJS,让我的生活更轻松。 (而且代码不那么干净了) 请帮忙。我被卡住了。

2 个答案:

答案 0 :(得分:5)

您必须使用Angular $http service。为了更好的抽象,你应该使用$resource service

var mod = angular.module('my-app', ['ngResource']);

function Controller($scope, $resource) {
  var User = $resource('http://serveraddress/users?from=:from&to=:to', null, {
      getAll: {method: 'JSONP', isArray: true}
    });

  $scope.changeDate = function(fromDate, toDate) {
    $scope.users = User.getAll({from: fromDate, to: toDate});
  };

  $scope.users = User.getAll();
}
<html ng-app="my-app">
<div ng-controller="Controller">
  <input type="text" my-date-picker="changeDate($startDate, $endDate)" />
  <table>
    <tr ng-repeat="user in users">
      <td>{{user.name}}</td>
      <td>{{user.address}}</td>
    </tr>
  </table>
</div>
</html>

为了适应DateSelector,您希望创建一个指令来封装其要求。最简单的一个是:

mod.directive('myDatePicker', function () {
    return {
    restrict: 'A',
        link: function (scope, element, attr) {
            $(element).daterangepicker({}, function (startDate, endDate) {
                scope.$eval(attr.myDatePicker, {$startDate: startDate, $endDate: endDate});
            });
        }
    };
});

无需担心同步。由于$资源基于promises,因此在数据就绪时它将自动绑定。

答案 1 :(得分:1)

你应该这样做:

Spring MVC Controller:

@RequestMapping(value="/load/{page}", method = RequestMethod.POST)  
public @ResponseBody String getCars(@PathVariable int page){  
            //remember that toString() has been overridden  
            return cars.getSubList(page*NUM_CARS, (page+1)*NUM_CARS).toString();  
}  

AngularJS控制器:

function carsCtrl($scope, $http){  
    //when the user enters in the site the 3 cars are loaded through SpringMVC  
    //by default AngularJS cars is empty  
    $scope.cars = [];  

    //that is the way for bindding 'click' event to a AngularJS function  
    //javascript cannot know the context, so we give it as a parameter  
    $scope.load = function(context){  
       //Asynchronous request, if you know jQuery, this one works like $.ajax  
       $http({  
              url: context+'/load/'+page,  
              method: "POST",  
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}  
       }).success(function (data, status, headers, config) {  
              //data contains the model which is send it by the Spring controller in JSON format  
              //$scope.cars.push is the way to add new cars into $scope.cars array  
              for(i=0; i< data.carList.length; i++)  
                 $scope.cars.push(data.carList[i]);  

              page++; //updating the page  
              page%=5; //our bean contains 15 cars, 3 cars par page = 5 pages, so page 5=0  

        }).error(function (data, status, headers, config) {  
              alert(status);  
        });             
    }  
} 

查看

<!-- Activating AngularJS in the entire document-->  
<html ng-app>  
    <head>  
        <!-- Adding AngularJS and our controller -->  
        <title>Luigi's world MVC bananas</title>  
        <link href="css/style.css" rel="stylesheet">  
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>  
        <script src="js/controller.js"></script><!-- our controller -->  
    </head>  
    <!-- Activating carsCtrl in the body -->  
    <body ng-controller="carsCtrl">  

         <div class="carsFrame">  

               <!-- AngularJS manages cars injection after have loaded the 3 first-->  
               <!-- We use ng-src instead src because src doesn't work in elements generated by AngularJS  -->  
               <div ng-repeat="car in cars" class="carsFrame">  
                   <img ng-src="{{car.src}}"/>  
                   <h1>{{car.name}}</h1>  
               </div>  
         </div>  

         <div id="button_container">  
               <!-- ng-click binds click event with AngularJS' $scope-->  
               <!-- Load function is implemented in the controller -->  
               <!-- As I said in the controller javascript cannot know the context, so we give it as a parameter-->  
               <button type="button" class="btn btn-xlarge btn-primary" ng-click="load('${pageContext.request.contextPath}')">3 more...</button>  
         </div>  
    </body>  
</html> 

完整的示例是here