Using AngularJS, I would like to create a list of options with radio buttons, the last of which has an empty text field labeled 'Other' for inputing an option that is not in the list. Here's a demonstration of what I have in mind that I bootstrapped in CodePen. Since Stack Overflow insists on including CodePen code in this message, here it is:
js:
angular.module('choices', [])
.controller("MainCtrl", ['$scope', function($scope) {
$scope.color = '';
$scope.colors = [
"Red",
"Green",
"Blue",
"Other"
];
$scope.changeColor = function(){
$scope.color = "Red"
};
}]);
html:
<html>
<head>
<body ng-app="choices" ng-controller="MainCtrl">
<div ng-repeat="color in colors">
<input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color">
<label>
{{color}}
</label>
<input type="text" ng-model="$parent.color" ng-show="color=='Other'">
</div>
<p></p>
The chosen color is <strong>{{color}}</strong>
<p></p>
<button ng-click="changeColor()">Change color</button>
</body>
</html>
Here is what I want this demo app to do:
- When I choose any option except for
Other, the text field should remain blank; - If I place cursor in the text field, the option
Othershould be selected - Once I start typing in the text field, the option
Othershould remain selected - If I change the model that registers the options (in the demo app achieved by clicking the
Change colorbutton), the corresponding radio button should be selected.
I achieved most of that functionality by using three models (one for color, one for keeping track of radio buttons and one for the Other field) and three watchers, but the resultant app seems brittle and fails some of the tests. Could you please suggest a better way for creating such a selector in Angular using as few models and watchers as possible?
(My question is somewhat similar to this SO question, but I hope is different enough not to be considered a duplicate.)