2014-03-26 56 views
0

我是新來,實際上我想問問是否有實施此行爲的清潔方法:角動態表單綁定

比方說,我有我要綁定到一個動態表單模型,例如,這種形式可以讓你創建一個書架。已經有名字和書籍列表
一個書架,然後每有我的名字作者
比方說,這將是確定一本書的形式,並與「加入書」按鈕,會顯示一個表單定義一個新的(只要你想,你可以添加儘可能多的)。

我想要達到的結果是一個像這樣的JSON:{name : "shelf1", books : [//json objects of books]}
有沒有一種方法可以正確地使用Angular實現這種行爲?在此先感謝

回答

1

角度可能有很多方法來解決這個問題。作爲新角色,我建議刷新一些術語(例如,指令如果不熟悉)。我想到的第一個解決方案(它傾向於緊跟問題領域)是爲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> 
+0

多麼美麗和完美的答案!非常感謝! –

0

這是非常可能無論你在你的問題說。要實現此目標,您必須使用指令。

以下是示例:

這是將重複您的控件的div。

<div class="form-group" data-ng-repeat="book in books"> 
    <label for="book" ng-show="showBookLabel(book)">Books</label> 
    <button ng-show="showAddBook(book)" ng-click="addNewBook()">Add another book</button> 
    <input type="text" ng-model="book.name" name="" placeholder="Enter a book name"> 
</div> 

控件動態插入發生,因爲這行代碼:

data-ng-repeat="choice in choices" 

NG-重複每一個隨時間重複從控制器的聲明是這樣的:

$scope.books = [{id: 'book1'}, {id: 'book2'}, {id: 'book3'}]; 

而在最後這是觸發並定義爲的點擊事件:

$scope.addNewBook = function() { 
    var newItemNo = $scope.books.length+1; 
    $scope.books.push({'id':'book'+newItemNo}); 
}; 

關於ng-repeat的更多詳細信息,你可以看到here