I am making a polling app using Angular and Node/Express/Mongo and would like to add a custom input field to add an option, when you select "I would like to add a custom option". I'm using ng-options to generate the voting options.
The HTML of the poll looks like this now: (poll is retrieved from database and added to $scope.poll.options:
<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>
A vote is attached to $scope.poll.vote and I use that to hit an EditPoll controller that talks to an API to update database.
If you are a logged in user + at your own poll: you can select a custom option from the dropdown and that shows a blank input field to add an option. I can't figure out what the code should be for that, any suggestions???
So for example:
I would like to vote for:
Here you can bind custom drop down item with specific text input field using watch feature we can update drop down filed data dynamically.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.