javascript 如何使 AngularJS REST 服务调用填充表并设置默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19622039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:13:01  来源:igfitidea点击:

How to make AngularJS REST service call to populate table and set default value

javascriptrestangularjs

提问by chapstick

I have an AngularJS frontend and REST (Jersey) backend that reads a list of book titles a teacher has assigned to a Student. There are two views/pages - list and edit. A list page is a table that shows Student Name and Currently Assigned Book Title.

我有一个 AngularJS 前端和 REST(泽西岛)后端,可以读取老师分配给学生的书名列表。有两种视图/页面 - 列表和编辑。列表页面是一个表格,显示学生姓名和当前分配的书名。

A teacher can select to edit the book assigned to a student. On selecting "Edit", teacher is taken to the Edit view/page that has a dropdown containing list of available book titles to read in the library and is populated by calling REST service Books.getUnassigned(). When a book is assigned to any student the backend will remove the book title from the unassigned list and add it to assigned list (Books.getAssigned()). So on the edit page I need to call the service, push the current assigned book title to that array and also set the default to the current book title.

教师可以选择编辑分配给学生的书籍。选择“编辑”后,教师将进入编辑视图/页面,该页面包含一个下拉列表,其中包含可供在图书馆阅读的可用书名列表,并通过调用 REST 服务 Books.getUnassigned() 填充。当一本书被分配给任何学生时,后端将从未分配列表中删除书名并将其添加到分配列表 (Books.getAssigned())。因此,在编辑页面上,我需要调用该服务,将当前分配的书名推送到该数组,并将默认值设置为当前书名。

  <select ng-model="bookToAssign">
                <option ng-repeat="book in available_books" value="{{book}}">{{book}}</option>
  </select>

Below is my service call. When the edit page is loaded $rootScope.args.arg contains a json object with all the data that needs to be passed from the previous page to the edit page - verified that the object is correct.

下面是我的服务电话。加载编辑页面时,$rootScope.args.arg 包含一个 json 对象,其中包含需要从上一页传递到编辑页面的所有数据 - 验证对象是否正确。

 $scope.available_books= NaiSvc.getUnassignedBooks.query(
        function(data){
            alert('success, got data: ', data);
            if($rootScope.args.arg !=null){
               data.push($rootScope.args.arg);  //verified this gets the right object
                $scope.bookToAssign.setDefault = data[data.length-1];
            }
        }, function(err){
            alert('request failed');
        }
    );

In function success callback when I try to do bookToAssign.setDefault, I get the error: TypeError: Cannot read property 'setDefault' of undefined. Can someone please guide me whats going on here? Appreciate the help

在函数成功回调中,当我尝试执行 bookToAssign.setDefault 时,出现错误:TypeError:无法读取未定义的属性“setDefault”。有人可以指导我这里发生了什么吗?感谢帮助

回答by mortalapeman

Base on your question, I've written up a working example that sound like what you want. Take a look at it and let me know if I missed something.

根据您的问题,我编写了一个听起来像您想要的工作示例。看看它,如果我错过了什么,请告诉我。

I've set up a landing page that lists some students and their books. I use a routes to pass data between views to setup the edit page. I used the ng-options directive to list the books and bind them accordingly.

我已经建立了一个登陆页面,其中列出了一些学生和他们的书籍。我使用路由在视图之间传递数据以设置编辑页面。我使用 ng-options 指令列出书籍并相应地绑定它们。

Demo plunker

演示plunker

Javascript:

Javascript:

angular.module('plunker', [])

.config(function($routeProvider) {
  $routeProvider.when('/list', {
    templateUrl: 'list.html',
    controller: 'ListCtrl'
  })
    .when('/edit/:book', {
      templateUrl: 'edit.html',
      controller: 'EditCtrl'
    })
    .otherwise({
      redirectTo: '/list'
    });
})


.service('BookService', function($q, $timeout) {
  var unassigned = ['English', 'History'];

  this.getUnassigned = function() {
    var deferred = $q.defer();

    // Simulate async call to server.
    $timeout(function() {
      deferred.resolve(unassigned);
    });

    return deferred.promise;
  };

})

.controller('EditCtrl', function($scope, $routeParams, BookService) {
  // student.book needs to be set to avoid null select option
  $scope.student = {book: $routeParams.book, name: $routeParams.name };
  $scope.unassigned = BookService.getUnassigned().then(function(data) {
    return [$routeParams.book].concat(data);
  });
})

.controller('ListCtrl', function($scope) {
  $scope.students = [{
    name: 'Billy',
    book: 'Math'
  }, {
    name: 'Joe',
    book: 'Science'
  }];
});

HTML:

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js" data-semver="1.1.5"></script>
    <script src="app.js"></script>
    <script type="text/ng-template" id="list.html">
      <table>
        <theader>
          <tr><td>Name</td><td>Book</td><td></td></tr>
        </theader>
        <tbody>
          <tr ng-repeat="student in students">
            <td>{{ student.name }}</td><td>{{ student.book }}</td><td><a ng-href="#/edit/{{ student.book }}?name={{student.name}}">Edit</a></td>
          </tr>
        </tbody>
      </table>
    </script>
    <script type="text/ng-template" id="edit.html">
      <div>
        <p>Current Student: {{ student.name }}</p>
        <label>Select A Book: </label>
        <select ng-model="student.book" ng-options="book for book in unassigned">
        </select>
        <p> You have selected: {{student.book}}</p>
    </script>
  </head>

  <body>
    <div ng-view></div>
  </body>
</html>