angular 回車事件新增資料到li

一個未來的大牛發表於2017-11-10
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title></title>  
  6.     <script src="js/angular.js"></script>  
  7.     </head>  
  8.     <body ng-app="myApp" ng-controller="myctrl">  
  9.     <input type="text" ng-model="textmodel" ng-keyup="mykey($event)"/>  
  10.     <ul>  
  11.     <li ng-repeat="x in list1 ">  
  12.     {{x}}  
  13. </li>  
  14. </ul>  
  15. <script>  
  16. var app = angular.module('myApp', []);  
  17. app.controller('myctrl', function ($scope) {  
  18.     $scope.list1 = ['1', '2', '3'];  
  19.     $scope.mykey = function (e) {  
  20.         var keycode = window.event ? e.keyCode : e.which;//獲取按鍵編碼  
  21.         if (keycode == 13) {  
  22.             $scope.myClick();//如果等於Enter鍵編碼執行方法  
  23.         }  
  24.     }  
  25.     $scope.myClick = function(){  
  26.         if(!arrindex($scope.list1,$scope.textmodel)){//不重複新增  
  27.             $scope.list1.push($scope.textmodel);  
  28.         }  
  29.     };  
  30. })  
  31. function arrindex(arr, obj) {//判斷是否重複  
  32.     var i = arr.length;  
  33.     while (i--) {  
  34.         if (arr[i] === obj) {  
  35.             return true;  
  36.         }  
  37.     }  
  38.     return false;  
  39. }  
  40. </script>  
  41. </body>  
  42. </html>  

相關文章