使用ng-repeat什么是能够编辑内容的最佳方法?
ng-repeat
在我理想的情况下, 添加的 生日将是一个超链接,点击该链接将显示一个编辑表单-与带有更新按钮的当前添加表单相同。
实时预览(插播)
HTML:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"> <title>Custom Plunker</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <script> document.write('<base href="' + document.location + '" />'); </script> <script src="app.js"></script> <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css" rel="stylesheet"> </head> <body ng-app="birthdayToDo" ng-controller="main"> <div id="wrap"> <!-- Begin page content --> <div class="container"> <div class="page-header"> <h1>Birthday Reminders</h1> </div> <ul ng-repeat="bday in bdays"> <li>{{bday.name}} | {{bday.date}}</li> </ul> <form ng-show="visible" ng-submit="newBirthday()"> <label>Name:</label> <input type="text" ng-model="bdayname" placeholder="Name" ng-required/> <label>Date:</label> <input type="date" ng-model="bdaydate" placeholder="Date" ng-required/> <br/> <button class="btn" type="submit">Save</button> </form> </div> <div id="push"></div> </div> <div id="footer"> <div class="container"> <a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a> </div> </div> </body>
App.js:
var app = angular.module('birthdayToDo', []); app.controller('main', function($scope){ // Start as not visible but when button is tapped it will show as true $scope.visible = false; // Create the array to hold the list of Birthdays $scope.bdays = []; // Create the function to push the data into the "bdays" array $scope.newBirthday = function(){ $scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate}); $scope.bdayname = ''; $scope.bdaydate = ''; }; });
您应该将表单放在每个节点内,分别使用ng-show和ng-hide启用和禁用编辑。像这样:
ng-show
ng-hide
<li> <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span> <form ng-show="editing" ng-submit="editing = false"> <label>Name:</label> <input type="text" ng-model="bday.name" placeholder="Name" ng-required/> <label>Date:</label> <input type="date" ng-model="bday.date" placeholder="Date" ng-required/> <br/> <button class="btn" type="submit">Save</button> </form> </li>
这里的关键点是:
ng-model
form
span
ng-click
editing
true
ng-submit
false
这是您更新的Plunker。