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