AngularJS - 如何使用表单添加到对象

AngularJS - how to add to an object using forms

这是我的 HTML:

<div ng-controller="BooksController as bookCtrl">
    <form ng-submit="bookCtrl.add()">
        <input type="text" ng-model="bookCtrl.book.name">
        <input type="text" ng-model="bookCtrl.book.rating">
        <input type="text" ng-model="bookCtrl.book.type">
        <input type="text" ng-model="bookCtrl.book.author">
        <input type="hidden" value="fa fa-keyboard-o fa-stack-1x" ng-model="bookCtrl.book.picture">
        <input type="submit" value="Add">
    </form>
</div>

这是我的 JS:

.controller("BooksController", ['BooksService', function(BooksService) {
    var self = this;
    self.getBooks = function() {
      return BooksService.getBooks();
   } 
    self.add = function(book) {
        alert(book.name);
        BooksService.add(book);
    };


}])

.factory("BooksService", [function() {
    var books = {
        1: {
            name: "k",
            review: "k",
            rating: 2,
            type: "k",
            author: "k",
            picture: "fa fa-keyboard-o fa-stack-1x",
            },
        2: {
            name: "b",
            review: "b",
            rating: 4,
            type: "b",
            author: "b",
            picture: "fa fa-code fa-stack-1x",
        }
    }

    return {
        getBooks: function() {
            return books;
        },
        add: function(book) {
            books[4] = book;
        }
    };
}])

这里的问题是,当我填写表格信息并尝试添加一本书时,这本书是未定义的。我试过

alert(book.name);

它给出了一个错误说

Cannot read property 'name' of undefined.

怎么没有定义?我想要做的是获取表单中提供的信息并将一本书添加到 "books" 对象。

将表单标签更改为

<form ng-submit="bookCtrl.add(bookCtrl.book)">

这里有两种选择。使用 this.book 控制器实例:

self.add = function() {
    alert(this.book.name);
    BooksService.add(this.book);
};

或将图书对象从 HTML 传递给控制器​​方法:

<form ng-submit="bookCtrl.add(bookCtrl.book)">
    <!-- ... -->
</form>

选择你喜欢的。我会说第一个更干净,不需要传递任何东西,因为它已经可用了。

评论正确地表明您没有在 ng-submit="bookCtrl.add()" 中传递图书对象。

您可以直接从 add 函数引用 bookCtrl.book 对象:

self.add = function() {
    alert(self.book.name);
    BooksService.add(self.book);
};

试试这个:

<form ng-submit="bookCtrl.add(bookCtrl.book)">

或者这样:

self.add = function() {
    alert(self.book.name);
    BooksService.add(self.book);};