角动态表单绑定

阿达纳

我是Angular的新手,实际上我想问一下是否有一种干净的方法来实现此行为:

假设我有一个要绑定到模型中的动态表单,例如,该表单可以让您创建书架。
一个书架有一个名字和一本书籍清单,然后每本书都有一个名字作者
假设这将是一种定义一本书的表格,并且带有“添加书”按钮,会向您显示一个表格来定义一本新书(您可以添加任意数量的)。

我想要达到的结果是一个JSON,例如:{name : "shelf1", books : [//json objects of books]}
是否可以使用Angular正确实现此行为?提前致谢

帕特里克

角度上可能有很多方法可以解决此问题。我是新手,不建议使用某些术语(例如,如果不熟悉,则使用指令)。我想到的第一个解决方案(并且趋向于紧跟问题领域)是为bookShelf和book都制定一个指令。这本书包含在一个书架中。参见jsfiddle

//define a module
var mod = angular.module("myApp", []);

//Main Controller
mod.controller("MainCtrl", function ($scope) {
    //empty shelves
    $scope.shelves = [];

    $scope.addShelf = function () {
        //make a new shelf
        $scope.shelves.push({name: "", books: []});
    }
});

//define a bookShelf directive
mod.directive("bookShelf", function () {
    return {
        restrict: "A",
        scope: {bookShelf: '='},
        template: 'Shelf Name: <input ng-model="bookShelf.name"><br><div ng-repeat="bk in bookShelf.books"><div class="book" book="bk"></div></div><button ng-click="addBook()">Add Book</button>',
        controller: function ($scope, $element, $attrs) {
            $scope.addBook = function () {
                $scope.bookShelf.books.push({name: "", author: ""});
            }
        }
    }
});

//define a book directive
mod.directive("book", function () {
    return {
        restrict: "A",
        scope: {book: '='},
        //Only requiring bookshelf here because a book is likely to be useless if not on a shelf.
        require: "^bookShelf",
        template: 'Book Name: <input ng-model = "book.name"><br>Author: <input ng-model="book.author">',
        link: function (scope, element, attrs) {
            //Not doing anything here yet
        }
    }
});

并示例HTML以使用它:

<div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-repeat="shelf in shelves">
        <div class="shelf" book-shelf="shelf"></div>
        Shelf JSON: {{shelf}}
        <br><br>
    </div>
    <br><br>
    <button ng-click="addShelf()">Add Shelf</button>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章