Add Select option dynamically in Angularjs - angularjs

I have a select list. I am populating the list using ViewBag.But for few cases it is required to add dynamic items to the selected list.
I am able to add those items but while those values are fetched it returns null for those newly added items.No problem with getting values for other items added using 'ViewBag'.
HTML:
<select ng-model="JobNo" id="JobNo" name="JobNo" class="myClass" style="width:100%;">
<option ng-repeat="item in JobList.Data" value="{{item.ProjectCode}}">{{item.ProjectDescription}}</option>
</select>
<input type="button" value="Save Data" ng-click="SaveData()">
Controller:
$scope.JobList = #Html.Raw(Json.Encode(ViewBag.ProjectCode))
//Added new item here
$compile(angular.element($("#JobNo option")).eq(0).after($compile('<option value="ALL"> -- ALL -- </option>')($scope)));
$scope.SaveData=function () {
alert($scope.JobNo); // it's show 'null' when I select "--ALL--" but no problem in other cases
}

In Controller add new item in Joblist.Data array at first index, instead of DOM injection.
$scope.JobList = #Html.Raw(Json.Encode(ViewBag.ProjectCode))
//Added new item here
$scope.JobList.Data.unshift({
ProjectCode: 'ALL',
ProjectDescription: ' -- ALL -- '
})
or
you can try add an option in html and remove option injection from controller, here is the codes,
html
<select ng-model="JobNo" id="JobNo" name="JobNo" class="myClass" style="width:100%;">
<option value="ALL"> -- ALL -- </option>
<option ng-repeat="item in JobList.Data" value="{{item.ProjectCode}}">{{item.ProjectDescription}}</option>
</select>
<input type="button" value="Save Data" ng-click="SaveData()">
controller
$scope.JobList = #Html.Raw(Json.Encode(ViewBag.ProjectCode))
$scope.SaveData=function () {
alert($scope.JobNo);
}

Try this:
<select ng-options="listname for refvar in displayname track by value" ng-model="selected value's variable"></select>

Related

Getting the Selected Object in Select Option in Angular

I have this array of objects which I put on the select option and I would want to select one list of object in the select option. However I can't get the value of that list of object. It outputs [object] [Object]. I want to get that selected list of object of the corporation. I assigned it to the [value] and it gets [object][Object].
<div class="select" >
<select class="form-control col-lg-8" #selectedValue (change)="assignCorporationToManage(selectedValue.value)">
<option *ngFor="let corporation of user_corporations" [value]="corporation">{{corporation.corp_name}}</option>
</select>
</div>
ts
assignCorporationToManage(selectedValue) {
console.log(selectedValue)
}
Try like this :
add ngModel for your select and use ngModelChange instead of change.
adding ngModel
using ngModelChange instead of change.
using [ngValue] instead of [value].
component.html
<select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue" (ngModelChange)="assignCorporationToManage($event)">
<option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
</select>
Component.ts
assignCorporationToManage(selectedValue) {
console.log(selectedValue)
}
you can get that particular object from the list by using selectedValue.
<select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue">
<option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
</select>
in your ts or js file,
const selectedObject = this.user_corporations.find((el: any) => {
return el?.corporation == this.selectedValue;
});
After that, you can use the selectedObject whatever you want.

How to display selected name in <p> from a Select dropdown and send selected id to controller in AngularJS?

I have the following select input in my html which is populated using ng-options. I want to show the selected NAME down below in whereas I want to send the selected ID back to the controller. I get the required id from ng-model="user.category". How can I show the selected name? I also show the names in options.
<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}">Select a Category</option>
</select>
<p>Available On : {{user.retailerBranchId}}</p>
<select ng-model="user.category" ng-options="category for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}">Select a Category</option>
</select>
<p>Available On : {{user.category.id}}</p>
If you make retailerBranchId a method you can do it with something like lodash' _.find() (or even native find). You have user.category updating according to your selection, which you say has the id in it, which you can use:
function retailerBranchId() {
return _.get(_.find(this.categories, { id: user.category }), 'name', '');
}
This also fails gracefully; if it can't find any name, or any item that matches the id, it'll return an empty string.
Edit: You would call it in a similar fashion like so:
<p>Available on: {{ user.retailerBranchId() }}</p>
Although really, it's better to use it like this:
<p data-ng-bind="'Available on: ' + user.retailerBranchId()"></p>
Can you try like a below method,
Controller to get selected Category Name:
$scope.getSelectedCategoryDetail=function(selectedCat){
angular.forEach($scope.categories, function(cat){
if(selectedCat===cat.id){
$scope.user.name=cat.name;
}
});
};
Template to have ng-change event:
<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control" class="select" required>
<option value="{{category.name}}" ng-change="getSelectedCategoryDetail(user.category)">Select a Category</option>
</select>
<p>Category Id : {{user.category}}</p>
<p>Category Name : {{user.name}}</p>

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.

how to update dropdown value dynamically

I have html code like this
<select id="userGroups" name="userGroups" ng-model="userGroups" required class="form-control">
<option value="{{grp.groupId}}" ng-repeat="grp in groups">{{grp.groupName}}</option>
</select>
and in my controller I want to set the default value but its not working
function CreateUserController($scope, grpList) {
$scope.groups = grpList.groupList; //it is loading correctly and dropdown is populating correctly
$scope.userGroups = "2";
}
I am trying to set the userGroups value to 2, but its always showing the first option in select
The best bet here is to use ng-options:
<select ng-model="userGroups"
ng-options="group.groupId as group.groupName for group in groups">
</select>
Fiddle

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