AngularJS:实现动态添加输入控件功能(转)
http://www.cnblogs.com/ilovewindy/p/3849428.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://code.jquery.com/jquery.js"></script> <script src="js/angular/angular.min.js"></script> <script src="SendSafeMessageController.js"></script> </head> <body ng-app="ftitApp"> <div class="form-group" ng-controller="SendSafeMessageController"> <label class="col-md-2 control-label">答复内容:</label> <div class="col-md-10"> <div ng-repeat="reply in fchat.replies"> <div class="form-group"> <div class="col-md-12"> <div class="col-md-1"> <label for="reply{{$index + 1}}">回答{{$index + 1}}</label> </div> <div class="col-md-9"> <input type="text" class="form-control" ng-model="reply.value" id="reply{{$index + 1}}" name="reply{{$index + 1}}" /> </div> <div class="col-md-2 img-link"> <a href="" ng-click="fchat.incrReply($index)"> <img src="img/plus.png" alt="plus" width="30px" height="30px" /> </a> <a href="" ng-click="fchat.decrReply($index)" ng-show="fchat.canDescReply"> <img src="img/minus.png" alt="minus" width="30px" height="30px"/> </a> </div> </div> </div> </div> <input type="hidden" id="replies" name="replies" value="{{fchat.combineReplies()}}" /> </div> </div> </body> </html>
SendSafeMessageController.js代码如下:
var ftitAppModule = angular.module('ftitApp', []); ftitAppModule.controller('SendSafeMessageController',function($scope,$log){ $scope.fchat = new Object(); $scope.fchat.replies = [{key: 0, value: ""}]; // 初始化时由于只有1条回复,所以不允许删除 $scope.fchat.canDescReply = false; // 增加回复数 $scope.fchat.incrReply = function($index) { $scope.fchat.replies.splice($index + 1, 0, {key: new Date().getTime(), value: ""}); // 用时间戳作为每个item的key // 增加新的回复后允许删除 $scope.fchat.canDescReply = true; } // 减少回复数 $scope.fchat.decrReply = function($index) { // 如果回复数大于1,删除被点击回复 if ($scope.fchat.replies.length > 1) { $scope.fchat.replies.splice($index, 1); } // 如果回复数为1,不允许删除 if ($scope.fchat.replies.length == 1) { $scope.fchat.canDescReply = false; } } $scope.fchat.combineReplies = function() { var cr = ""; for (var i = 0; i < $scope.fchat.replies.length; i++) { cr += "#" + $scope.fchat.replies[i].value; } cr = cr.substring(1); // $log.debug("Combined replies: " + cr); return cr; } });