繁体   English   中英

如何使用带有SpringMVC的AngularJS异步加载数据?

[英]How to load data asynchronously using AngularJS with SpringMVC?

我是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标记遍历列表并以表格形式向用户显示数据

<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. 用户可以选择日期范围,并根据所选范围(例如今天,昨天,上周,上个月,自定义范围)进行选择,显示的数据应更新。

我的操作方式:我正在使用Bootstrap-Daterangepicker( https://github.com/dangrossman/bootstrap-daterangepicker )显示标记。 它为我提供了一个回调函数。

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

例如$('#reportrange').daterangepicker(options, function(startDate, endDate){});

没有AngularJS,这将是混乱的。 我可以调用jQuery ajax,然后获取列表,然后从jQuery中弄乱DOM元素。 但这很混乱。

在这种情况下,如何包含AngularJS可以使我的生活更轻松。 (而且代码更简洁),请帮忙。 我被卡住了。

您必须使用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});
            });
        }
    };
});

无需担心同步。 由于$ resource是基于promises的 ,因此当数据准备就绪时,它将自动绑定。

您应该执行以下操作:

SpringMVC控制器:

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

完整的示例在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM