如何使用ng-options在AngularJS中添加一个输入字段到特定的选择字段



我正在使用Angular和Node/Express/Mongo制作一个投票应用程序,并想添加一个自定义输入字段来添加一个选项,当你选择"我想添加一个自定义选项"时。我使用ng-options来生成投票选项。

投票的HTML现在看起来是这样的:(poll从数据库中检索并添加到$scope.poll。选择:

<div class="container">
  <div class="panel panel-default">
    <div class="panel-body">
      <div class="row">
        <div class="col-md-6">
          <h2>
            {{poll.title}}
          </h2>
          <h5>
            Created by: {{poll.displayName}}
          </h5>
          <form>
            <div class="form-group">
              <label for="vote">I would like to vote for:</label>
              <select class="form-control" id="vote" ng-model="poll.vote" ng-options="item.option as item.option for item in poll.options">
              </select>
            </div>
            <div class="form-group" ng-show="userID === poll.userID">
             <br>
               <label for="vote">Vote with my own option</label>
               <input ng-model="poll.vote" placeholder="Your own option" class="form-control" type="text">
            </div>   
            <button type="submit" class="btn btn-primary" ng-click="votePoll(poll)">Vote</button>
          </form>
          </br>
        </div>
        <div class="col-md-6">
          <canvas id="myChart" width="400" height="400">
          </canvas> 
        </div>
      </div>
    </div>
  </div>
 </div>

投票附加到$scope.poll。我用它来命中一个EditPoll控制器,它与API对话来更新数据库。

如果你是一个登录用户+在你自己的投票:你可以从下拉菜单中选择一个自定义选项,它会显示一个空白的输入字段来添加一个选项。我不知道代码应该是什么,有什么建议吗??

例如:

我想投票给:

  • Option1
  • Option2
  • Option3
  • 我想要一个自定义选项>在
  • 下面显示一个空白输入字段

这里你可以绑定自定义下拉项与特定的文本输入字段使用手表功能,我们可以动态更新下拉字段的数据。

var app=angular.module("myApp",[]);
app.controller("FirstController",function($scope){
	
	
	$scope.items = [{
	  id: 'opt_1',
	  label: 'aLabel',
	  subItem: { name: 'aSubItem' }
	}, 
	{
	  id: 'opt_2',
	  label: 'bLabel',
	  subItem: { name: 'bSubItem' }
	}, 
	{
	  id: 'opt_custom',
	  label: 'I would like a custom option',
	  subItem: { name: 'bSubItem' }
	}];
	
  $scope.checkOptions=function(){
   // alert($scope.selected.id);
    if($scope.selected.id=='opt_custom'){
	$scope.$watch('custom', function(newValue, oldValue) {
		debugger;
		$scope.items[2].id='opt_custom_'+$scope.custom;
		$scope.items[2].label=$scope.custom;
	});
      }
    }
})
<html ng-app="myApp">
<head>
<title>Simple App</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
<div ng-controller="FirstController">
<select ng-change="checkOptions()" ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
 <input ng-model="custom" placeholder="Your own option" class="form-control" type="text">
</div>
</body>
</html>

最新更新