Spring:从JSTL(forEach)转换为angular.js(ng repeat)



我是angular.js的新手,我有一个spring MVC应用程序,我想从jstl切换到angular.js,我是这样开始的

<table>
        <c:forEach var="list" items="${list}">
            <tr class="alt" ><td >${list.name}</td><td >${list.value}</td> </tr> 
        </c:forEach>
 </table>

 <table ng-app="" id="users">
        <tr ng-repeat="x in list">
             <td>{{ x.name }}</td>
            <td>{{ x.value }}</td>
        </tr>
 </table>

如果真的想直接用HTML编写信息,可以添加一个带有所需脚本的标记。

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
      angular.module('AppNameHere', [])      
      .controller('exampleController', function() {
        this.list = [{
            name: 'Fool',
            value: '12'
          },
          {
            name: 'Bar',
            value: '15'
          }];
      });
    </script>
  </head>
  <body ng-app="AppNameHere">
    <table id="users" ng-controller="exampleController as example">      
      <tr ng-repeat="x in example.list">
        <td>{{ x.name }}</td>
        <td>{{ x.value }}</td>
      </tr>
    </table>
  </body>
</html>

但是,正如@Vaelyr所说,AngularJS通常用于从服务器获取数据(使用ajax或类似的方法),并在页面上显示结果:

// By default, you can use only 1 module per page.
angular.module('AppNameHere', [])
  // service to load the data from server
  .factory('exampleFactory', function($q){
    var deferred = $q.defer();
    
    // TODO: Load async...
    var list = 
      [{
        name: 'Fool',
        value: '12'
      },
      {
        name: 'Bar',
        value: '15'
      }];
    
    deferred.resolve(list);
    
    return deferred.promise;
  })
  // controller to show the data on the page
  .controller('exampleController', function(exampleFactory) {
    var controller = this;
    controller.list = [];
    
    // When the data is fetched from the server...
    exampleFactory.then(function(list) {
      // bind to the page
      controller.list = list;
    });
  });
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body ng-app="AppNameHere">
    <table id="users" ng-controller="exampleController as example">      
      <tr ng-repeat="x in example.list">
        <td>{{ x.name }}</td>
        <td>{{ x.value }}</td>
      </tr>
    </table>
  </body>
</html>

最新更新