AngularJS: Show Textfield depending on Select Option - angularjs

I have a Dropdown with Differnt Options (Numbers). If a number was selected, an amount of textfields should be shown depending on the number that was selected before.
Example:
User selects number = 2
There should be two time a textfield called "name"
<select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
<option value="0">---Please select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select><br>
<div ng-repeat="t in vm.getTimes({{data.singleSelect}}) track by $index">
{{$index}}
<input ng-model="text1" /> <!-- this textfield should be repeated--></div>
Function getTimes in the controller:
vm.getTimes = function (n) {
return new Array(n);
};
I can´t pass vm.getTimes the selected option - why not?
If I write an INT for {{data.singleSelect}} in the function getTimes, it works.

Your getTimes function should be like this.
getTimes = function (n) {
if(n){
return new Array(parseInt(n));
}else{
return 0;
}
}
Why it is not working?
The parameter you passing create array of length initialised using
with the same value.
Because n is string.
You need to parse it to Integer.
Check JavaScript#Array.
Here is the working plunker

You ve a fixed number of options so you can use limitTo
var app = angular.module("app", [])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
<option value="0">---Please select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br>
<div ng-repeat="t in [1,2] | limitTo:data.singleSelect track by $index">
{{$index}}
<input ng-model="text1" />
<!-- this textfield should be repeated-->
</div>
</div>

You are trying to create a new array based on the input (that you assume is a number), but you never ensure that this will indeed be one.
For example:
t in getNumber(data.singleSelect * 1) track by $index would solve it, or
$scope.getNumber = function (num) {
return new Array(parseInt(num));
}
would also make your loop function properly.
What you're trying to do:
> new Array("2")
< ["2"]
What you should do:
> new Array(2)
< [undefined × 2]
//don't worry about undefined for now, but this array has 0 and 1 elements.
Here's an updated fiddle with your sample: https://plnkr.co/edit/rPhFnmmKNvHtSirGCYHG?p=preview

Related

How to remove item from an array

I have a dropdown where items are populated from $scope.role. Now I need to remove the values from $scope.role once the value is added or selected in dropdown. I did splice(index,1) which actually delete the first element only. Need assistance.
$scope.role = ['Actor', 'Director/ Asst. director', 'Lyricist',
'Music director/ Asst. director', 'Singer', 'Standup Comedian', 'Model',
'Cinematographer', 'Photographer', 'Script Writer', 'Choreographer',
'Editor/ Promo editor', 'Costume designer', 'Art director', 'Stunt artist',
'Voice-over artist', 'Graphic Designer', 'Screenplay', 'Dialogue',
'Back ground music'];
Html:
<div class="row newRow">
<div class="form-group fields col-sm-2 col-xs-4">
<label>ROLE *</label>
<select name="role" class="form-control1 drop2" required ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
<div class="form-group col-sm-2 col-xs-4">
<button ng-click="AddRole()">Click to Add Role</button>
</div>
</div>
JS:
$scope.multiRoles = [];
$scope.role == $scope.dummy;
$scope.rolesAdded = false;
$scope.AddRole = function(index) {
debugger;
if ($scope.model.role !== undefined) {
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index, 1);
console.log($scope.role);
}
};
You can do it in two ways 1) As suggested by #nikjohn by sending your $index of dropdown in ng-click = "AddRole($index)" and then splice or else
2) You can find the index of the selected option by using the ng-model binded to the dropdown.
$scope.AddRole = function(){
debugger;
if($scope.model.role !== undefined ){
$scope.multiRoles.push($scope.model.role);
var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
$scope.role.splice(index,1);
console.log($scope.role);
}
};
In your HTML, pass $index to the AddRole. Otherwise, the function does not know what $index is, and also include the button within the ng-repeat:
<select name="role"
class="form-control1 drop2" required
ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}"> {{item}}
<button ng-click = "AddRole($index)">Click to Add Role</button>
</option>
</select>
In your Controller, there's an extra = that I've highlighted in my comment:
$scope.multiRoles = [];
$scope.role == $scope.dummy; // Why a `==` here? This should be a `=`
$scope.rolesAdded = false;
$scope.AddRole = function(index){
debugger;
if($scope.model.role.length){ // Cleaner method to verify that the array is non-empty
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index,1);
console.log($scope.role);
}
};
May I also suggest that you use Angular's select implementation with ng-options because:
Choosing between ngRepeat and ngOptions
In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:
more flexibility in how the <select>'s model is assigned via the select as part of the comprehension expression
reduced memory consumption by not creating a new scope for each repeated instance
increased render speed by creating the options in a documentFragment instead of individually
Specifically, select with repeated options slows down significantly starting at 2000 options in Chrome and Internet Explorer / Edge.

Dynamic dropdown using ng-repeat in Angular

My application gives users the option to choose from several dropdown menus and the third menu should be dynamic depending on the selection from the previous two menus.
I am using ng-repeat and ng-if to set the condition like this
// First dropdown menu
<select ng-model="letter" class = "form-control">
<option ng-repeat= "letter in letters" value = "letter">{{letter}}</option>
</select>
<br>
// second dropdown menu
<select ng-model="number" class = "form-control">
<option ng-repeat = "number in numbers" value = "number">{{number}}</option>
</select>
<br>
// third dropdown menu
<select ng-model="color" class="form-control">
<option ng-repeat="A1_color in A1_colors" ng-if= "letter = A & number = 1" value="{{A1_color}}">{{A1_color}}</option>
</select>
...
<select ng-model="color" class="form-control">
<option ng-repeat="B2_color in B2_colors" ng-if= "letter = B & number = 2" value="{{B2_color}}">{{B2_color}}</option>
</select>
In my controller, I have the lists like this
$scope.letters = {'A', 'B'};
$scope.numbers = {'1', '2'};
$scope.A1_colors = {'red', 'pink'};
$scope.A2_colors = {'blue', 'black'};
$scope.B1_colors = {'yellow', 'orange'};
$scope.B2_colors = {'white', 'black'};
So if the user selects 'A' from the first menu and '2' from the second menu, he should see the options for 'A2_colors' in the third menu. What is the right way to do this?
I think, why to use ng-repeat for <select> tag when angular have another directive ng-options. You should use ng-options instead of ng-repeat. Never the less, you can also use ng-repeat, but it's not good way to do standard coding.
Syntax for ng-options:
<select ng-model="item"
ng-options="item as item for item in collection">
</select>
Your problem will solved by following code:
<div ng-app="MyApp" ng-controller="ctrl">
<select ng-model="letter"
ng-options="letter as letter for letter in letters">
</select>
<select ng-model="number"
ng-options="number as number for number in numbers">
</select>
<select ng-model="color"
ng-options="color as color for color in colors">
</select>
</div>
The "right way" is pretty subjective. Is this just a smaller example of what will be a larger collection of letters, numbers and colors? Here is one way you could approach it where you won't have to create a whole bunch of <select></select> elements that you show or hide.
JS:
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colors = {
'A1': ['red', 'pink'],
'A2': ['blue', 'black'],
'B1': ['yellow', 'orange'],
'B2': ['white', 'black']
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelection =
colors[$scope.selectedLetter + $scope.selectedNumber];
}
}
});
HTML:
<div ng-app="app" ng-controller="ctrl">
<select ng-model="selectedLetter"
ng-change="setColorSelection()"
ng-options="letter as letter for letter in letters">
</select>
<select ng-model="selectedNumber"
ng-change="setColorSelection()"
ng-options="number as number for number in numbers">
</select>
<select ng-model="selectedColor"
ng-if="colorSelection.length"
ng-options="color as color for color in colorSelection">
</select>
</div>

Propagate a Select with angularJS and read the option

I have a problem to read the information selected that is propagate in a select.
<div ng-show="deviceDetail != null" ng-model="example" >
<select >
<option value="NONE">Select</option>
<option ng-repeat="option in deviceDetail" ng-change="selectOption()">{{option}}</option>
</select>
<br/>
The value of the selection is: {{example}}
</div>
this is the HTML code and in the {{example}} I want to see the information that the user selected.
this is the part of the js releted:
$scope.selectOption = function() {
$scope.example = option.productName;
};
How I can fix it?
Thanks a million!
Set your example scope variable directly in <select> instead calling ng-change event and assigning into that function.
You can directly set option.name to example model with the use of ng-options too.
Here You have applied ng-model directive to div tag.
<div> is not input element so apply ng-model to <select> element here.
I would suggest to use ng-options directive for filling the selection list in <select>. ng-repeat is also fine.
Here you are binging ng-change event so in the function if requires then you can pass the object on which event is triggering so you can use that object or perform any operation on that.
Below is the modified template.
<div ng-show="deviceDetail != null">
<select >
<option value="NONE">Select</option>
<option ng-model="example" ng-options="option in deviceDetail" ng-change="selectOption(option)">{{option}}</option>
</select>
<br/>
The value of the selection is: {{example}}
</div>
You should to pass current option:
<select >
<option value="NONE">Select</option>
<option ng-repeat="option in deviceDetail" ng-change="selectOption(option )">{{option}}</option>
</select>
$scope.selectOption = function(option) {
$scope.example = option; // is there property .productName?;
};
Try this:
<div ng-show="deviceDetail != null">
<select >
<option value="NONE">Select</option>
<option ng-model="option" ng-options="option in deviceDetail" ng-change="selectOption(option)">
{{option}}</option>
</select>
<br/>
The value of the selection is: {{example}}
Js:
$scope.selectOption = function(option) {
$scope.example = option;
};
You should use ng-options
The value of the selection is: {{example}}

Synchronize the parameter of a dynamic select list in AngularJS

I have a form with a dynamically generated select list. The values for this list are retrieved from the scope. The currently selected value is also retrieved from the scope.
Unfortunately, there is a synchronization issue.
Below this is illustrated. The dynamic select list shows 1 as selected, but the param is 2. The static select list shows the correct value.
angular.module('fiddle', [])
.controller('Ctrl', function($scope) {
$scope.xs = [1,2,3];
$scope.param = 2;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="fiddle" ng-controller="Ctrl">
Correct representation:
<select ng-model="param">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
Incorrect representation:
<select ng-model="param">
<option ng-repeat="x in xs" value="{{x}}">{{x}}</option>
</select><br>
param: {{param}}
</body>
As I was properly formulating my question, as often, I found the solution already.
I should use ng-options instead of ng-repeat on the option tag.
<select ng-model="param" ng-options="x for x in xs">
</select>
https://docs.angularjs.org/api/ng/directive/select

Angularjs - Populate select box using ng-options

I have a json object as below
keyword = {
application: ["Athena","EWindow","EWS","FACT","FTP","Hardware","PEN","Hermes","Infrastructure","LNG Tracker","M2M","Maintenance","Microsite","Oracle","Platts.com","PMC","PTO Task","Sametime","Third Party Data","User Error","Vendor","Web Channels","XML-DD","Customer Request","Mark Logic","SBB","Market Engagement Form","Lotus Notes Database","Oracle11i","External News","Stringers","PRP","Kingsman","Hermes-1"],
incidentType: ["Publishing Failure","Brand Damage","Security Failure","Content Creation Failure","Internal failure","External Failure","System Failure","Operational Failure","Editorial Failure","Content inaccuracy","Process Failure","Application Issue","Infrastructure Issue","User Issue","Other","Resend","Data Send validation","Customer issue"],
incidentEnvironment: ["Production","Non-Production","Others"],
incidentPriority: ["Low","Medium","High","Critical"],
incidentLocation: ["Asia Pacific","Europe","New York","New Jersey","Houston","Washington DC","Others"],
incidentStatus: ["Initiation","Work In Progress","Completed","On Hold","Closed","Cancelled"],
incidentCategory: ["ActiveX","Checkin","Checkout","CKEditor","Corrupt Story","Delete Story","Delivering Content","Download-Upload","Filter","Graph-Rich Media","IE Cache","IE Setting","Indicia","InDesign","Infrastructure","Ingest(Table)","Other","PDF","Publish","Search","Table","User Issue"],
incidentTicketTools: ["BMC Remedy"],
}
<div class="col-lg-3">
<select name="txt_inc_Status" class="form-control input-sm" required>
<option selected disabled>
-- Select Status --
</option>
<option ng-repeat="incidentStatus in keywords.incidentStatus" value="{{incidentStatus}}">
{{incidentStatus}}
</option>
</select>
</div>
I need to populate these values in select boxes. Ex: Keywords.application in application select box and so on.
Earlier I used ng-repeat to construct options. But I came to know that it is not advised to do so.
So I am trying to use ng-option but facing difficulties in populating this. Can somebody help me on this?
Also I need to select a default value (random) for these selectbox. How can that be achieved. It didn't work when I used ng-repeat
You can use
<div ng-repeat="(key, value) in keywords">
<select ng-options="item for item in value" ng-init="index = getRandomIndex(value)" ng-model="value[index]">{{item}}</select>
</div>
together with a function to get the random index for current array
$scope.getRandomIndex = function(item){
var index = Math.floor((item.length * Math.random()));
return index;
}
DEMO

Resources