抽奖小程序流程_AngularJS完成动态添加Option的方法

2021-01-12 11:16 jianzhan
AngularJS实现动态添加Option的方法       这篇文章主要介绍了AngularJS实现动态添加Option的方法,涉及AngularJS事件响应及页面元素动态操作相关实现技巧,需要的朋友可以参考下

本文实例讲述了AngularJS实现动态添加Option的方法。分享给大家供大家参考,具体如下:

项目中后台管理设置,前台下拉动态添加option

 !DOCTYPE html 
 html lang="zh-CN" 
 head 
 meta charset="utf-8" 
 meta http-equiv="X-UA-Compatible" content="IE=edge" 
 meta name="viewport" content="width=device-width, initial-scale=1" 
 link rel="stylesheet" href="bootstrap.min.css" rel="external nofollow" 
 script src="jQuery.min.js" /script 
 script src="angular.js" /script 
 script src="angular-animate.js" /script 
 script src="bootstrap.min.js" /script 
 script type="text/JavaScript" 
 var app = angular.module('myapp', []);
 app.controller('DemoCtrl', function ($scope) {
 $scope.optionContainer = [];
 var realOptions = [];
 var randomCode = function() {
 var chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKMNOPQRSTUVWXYZ";
 var randomChars = "";
 for (var i = 0; i i++) {
 var index = Math.floor(Math.random() * chars.length);
 randomChars = randomChars + chars.charAt(i);
 return randomChars;
 var getIndex = function(array, id) {
 var tmpItem = {};
 angular.forEach(array, function(item) {
 if (item.id == id) {
 tmpItem = item;
 return array.indexOf(tmpItem);
 $scope.add = function() {
 var optionIndex = randomCode();
 $scope.optionContainer.push({
 id : optionIndex,
 readOnly : false,
 content : '',
 showConfirm : true
 console.log($scope.optionContainer)
 $scope.confirm = function(content, id) {
 if (content == '') {
 return;
 var flag = false;
 angular.forEach(realOptions, function(item) {
 if (item == content) {
 flag = true;
 if (flag) {
 console.log('already exist!');
 return;
 var tmpIdIndex = getIndex($scope.optionContainer, id);
 realOptions.push(content);
 $scope.optionContainer[tmpIdIndex].showConfirm = false;
 $scope.optionContainer[tmpIdIndex].readOnly = true;
 $scope.deleteFunc = function(id) {
 var tmpIdIndex = getIndex($scope.optionContainer, id);
 if ($scope.optionContainer[tmpIdIndex].showConfirm == false) {
 tmpIndex = realOptions.indexOf($scope.optionContainer[tmpIdIndex].content);
 realOptions.splice(tmpIndex, 1);
 $scope.optionContainer.splice(tmpIdIndex, 1);
 /script 
 /head 
 body ng-app="myapp" 
 div ng-controller="DemoCtrl" 
 div 
 div 
 h1 create options /h1 
 /div 
 div 
 div 
 table 
 thead 
 th option /th 
 /tr 
 /thead 
 tbody 
 tr ng-repeat="item in optionContainer" 
 input type="text" ng-model="item.content" ng-readonly="item.readOnly"/ /td 
 button type="button" ng-click="confirm(item.content, item.id)" ng-show="item.showConfirm" Confirm
 /button 
 /td 
 button type="button" ng-click="deleteFunc(item.id)" Delete
 /button 
 /td 
 /tr 
 /tbody 
 /table 
 /div 
 a ng-click="add()" Add /a 
 /div 
 /div 
 /div 
 /body 
 /html 

运行效果图如下:

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《》、《》及《》

希望本文所述对大家AngularJS程序设计有所帮助。