功能要求如下:
1. 點擊加號可以增加輸入框。
2. 點擊減號可以減少輸入框。
3. 當輸入框只有一個的時候,不能再減少輸入框。
效果圖如下:
只有一個輸入框
有多個輸入框
要實現這個功能,可以用angularJS實現。實現步驟如下:
1. 在HTML中引入script
<script type='text/javascript' src='path/to/angular.min.js'></script>
2. HTML部分代碼如下:
1 <div class="form-group" ng-controller="SendSafeMessageController"> 2 <label class="col-md-2 control-label">答復內容:</label> 3 <div class="col-md-10"> 4 <div ng-repeat="reply in fchat.replies"> 5 <div class="form-group"> 6 <div class="col-md-12"> 7 <div class="col-md-1"> 8 <label for="reply{{$index + 1}}">回答{{$index + 1}}</label> 9 </div> 10 <div class="col-md-9"> 11 <input type="text" class="form-control" ng-model="reply.value" 12 id="reply{{$index + 1}}" name="reply{{$index + 1}}" /> 13 </div> 14 <div class="col-md-2 img-link"> 15 <a href="" ng-click="fchat.incrReply($index)"> 16 <img src="/images/plus.png" alt="plus" width="30px" height="30px" /> 17 </a> 18 <a href="" ng-click="fchat.decrReply($index)" ng-show="fchat.canDescReply"> 19 <img src="/images/minus.png" alt="minus" width="30px" height="30px"/> 20 </a> 21 <img src="/images/dis_minus.png" alt="minus" width="30px" height="30px" 22 ng-show="!fchat.canDescReply"/> 23 </div> 24 </div> 25 </div> 26 </div> 27 <input type="hidden" id="replies" name="replies" value="{{fchat.combineReplies()}}" /> 28 </div> 29 </div>
SendSafeMessageController.js代碼如下:
1 var ftitAppModule = angular.module('ftitApp', []); 2 3 ftitAppModule.controller('SendSafeMessageController', 4 function ($scope, $log) { 5 $scope.fchat = new Object(); 6 $scope.fchat.replies = [{key: 0, value: ""}]; 7 // 初始化時由於只有1條回復,所以不允許刪除 8 $scope.fchat.canDescReply = false; 9 10 // 增加回復數 11 $scope.fchat.incrReply = function($index) { 12 $scope.fchat.replies.splice($index + 1, 0, 13 {key: new Date().getTime(), value: ""}); // 用時間戳作為每個item的key 14 // 增加新的回復后允許刪除 15 $scope.fchat.canDescReply = true; 16 } 17 18 // 減少回復數 19 $scope.fchat.decrReply = function($index) { 20 // 如果回復數大於1,刪除被點擊回復 21 if ($scope.fchat.replies.length > 1) { 22 $scope.fchat.replies.splice($index, 1); 23 } 24 // 如果回復數為1,不允許刪除 25 if ($scope.fchat.replies.length == 1) { 26 $scope.fchat.canDescReply = false; 27 } 28 } 29 30 $scope.fchat.combineReplies = function() { 31 var cr = ""; 32 for (var i = 0; i < $scope.fchat.replies.length; i++) { 33 cr += "#" + $scope.fchat.replies[i].value; 34 } 35 cr = cr.substring(1); 36 $log.debug("Combined replies: " + cr); 37 38 return cr; 39 } 40 } 41 );
需要注意的是,由於輸入框是動態添加,所以事先我們是不知道到底有多少數據是可以傳給服務器的,所以在js中用了一個combineReplies函數來將所有的輸入框內容合並成一個數值,用#作為分隔符分開,然后放到一個hidden輸入框中來傳值給服務器。
