AngularJS: need to split/parse ng-options value - angularjs

A legacy database I am working with stores lookup values in a semi-colon separated list (within a single field/column in the table) - which worked fine as a data source for an ASP.NET. But for migrating to AngularJS - I've found no way to intercept the value and split it for separate options in the select element.
In the select drop down it simply shows (for example) "1 rep; 2 reps; 3 reps" etc.
Can anyone suggest how to split this value so the select options render vertically - each one in it's own option row?
This is how the select element looks now:
<select
ng-model="exerciseVals[$index].reps1" ng-options="value.REPS as value.REPS for (key,value) in lkps
></select>

ng-options works on an array or an object.
If I understand your situation correctily, you're getting a large string from the server with semicolon-separated entries. You need to split it into an array.
$scope.lkps = stringFromServer.split(";");
Then in HTML:
<select ng-model="selectedVal"
ng-options="item for item in lkps">
</select>

You can try This , i have included in my code too !
Working Code
<div ng-app>
<div ng-controller="tempCtrl">
<select>
<option ng-repeat="temp in tempdata">
{{temp}}
</option>
</select>
</div>
</div>
JS CODE
var myApp = angular.module('App', ["xeditable"]);
myApp.controller('tempCtrl',function ($scope) {
alert();
$scope.tempdata = ["1 rep","2 rep","3 rep"];
console.log($scope);
});

You can also use angular filter :
<select ng-model ='select' ng-options="item for item in 'd;g;f'|split:';'">
<option value="">Nothing selected</option>
</select>
JS:
myApp.filter('split',function(){
return function(str,delimeter)
{
return str.split(delimeter);
}
check working example

Related

ng-selected not working in select field

I am trying to set the default value of a select field to a set option but its not working and I can't seem to figure out what am I doing wrong?
In my controller I have:
$scope.interp_id = "2"; // set the default id
$http.get("web/controllers/get.php")
.then(function (response) {
$scope.interpreters = response.data.records;
});
get.php is a php file that returns json (this is working properly).
My select looks like:
<select ng-model="interpreters_id">
<option ng-repeat="x in interpreters" value="{{x.id}}" ng-selected="{{x.id == interp_id}}">{{x.first_name}} {{x.middle_name}} {{x.last_name}}</option>
</select>
When I go to view it in my browser it looks like:
but when I inspect the element it shows that option ng-selected is True.
what am I doing wrong?
ngOptions is the recommended way to use select elements in Angular.
Also, if you look at the ngSelected documentation there is a yellow box that states that it does not work properly with the select and ngModel properties which is, in a way, what you are trying to do.
ngRepeat will gladly repeat your option elements however it is not the correct way to work with a select element.
I have prepared a fiddle for you to try it out.
<div ng-app="ngOptionsApp">
<div ng-controller="ExampleController">
<select ng-model="selectedInterpreter" ng-options="interpreter as interpreter.name for interpreter in interpreters track by interpreter.id">
<option value="">Select an Interpreter</option>
</select>
{{selectedInterpreter}}
</div>
</div>
angular.module('ngOptionsApp', []).controller('ExampleController', ['$scope', function($scope) {
$scope.interpreters=[{id: 1, name:'Gill Bates'}, {id: 2, name:'Cohn Jarmack'}, {id: 3, name:'Melon Musk'}];
$scope.selectedInterpreter = $scope.interpreters[0];
}]);
Hope it helps ;)
You should not use the curly braces in ng-selected directive. May you try this?
<option ng-repeat="x in interpreters" value="{{x.id}}" ng-selected="x.id == interp_id">{{x.first_name}} {{x.middle_name}} {{x.last_name}}</option>
http://jsfiddle.net/endrcn/44j19ngp/

Angular Select Tags

I am creating a select tag in angular. According to many sites I have read and some posts on here, it says when using the select tag to not use "ng-repeat" on the option tag but use "ng-options" on the select tag so that is how I set it up. My question is, I want a specific option tag selected by default, how do i set the selected attribute using this method?
<select class="form-control" ng-model="selected_group" ng-change="new_group($event)" ng-options="group as (group.group_name | decodeuri) for group in groups"></select>
Choosing a default is easy: set selected_group equal to a particular group in your controller.
The basic idea is that you have a collection and the selected option is to be stored in your ng-model. To designate a selection from the start, you need to put something in ng-model. That would have to be in your controller.
You could add an <option> tag:
<select class="form-control" ng-model="selected_group" ng-change="new_group(selected_group)" ng-options="group as (group.group_name | decodeuri) for group in groups">
<option value="">Please Select an Option</option>
</select>
Here I have created small working demo
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" ng-model="option.group" ng-options="group as (group.name | myfilter) for group in groups">
</select>
</div>
var app = angular.module('myApp', []);
app.filter('myfilter', function() {
return function(v) {
return v == 'test3' ? 'filtered test3' : v;
};
});
app.controller('myCtrl', function($scope) {
$scope.groups = [{id:1,name:'test1', phone:'1234567890'},
{id:2,name:'test2', phone:'1234567890'},
{id:3,name:'test3', phone:'1234567890'}
];
$scope.option={
group: $scope.groups[1]
}
});

How do I get the ng-model of a select tag to get the initially-selected option?

I'm pretty new to Angular, so I may be going about this all wrong...
I have a <select> similar to the following:
<select ng-model="mySelectedValue">
<option value="">--</option>
<option ng-repeat="myValue in someDynamicArrayOfValues" value="{{myValue}}" ng-selected="myFunctionForDeterminingWhetherValueIsSelected(myValue)">{{myValue}}</option>
</select>
This mostly works... The dropdown initially renders with the correct option selected, and if I change the selected option, then mySelectedValue will get the new selection. However, mySelectedValue does NOT get the initially-selected option. mySelectedValue is blank until I change the value in the dropdown.
I looked at ng-init, but that seems to get evaluated before someDynamicArrayOfValues is set...
Is there a way I can get mySelectedValue to receive the value in the initially-selected <option>?
UPDATE:
I forgot to mention that I had also tried using ng-options, but haven't had any luck getting that to work in conjunction with determining which option was selected.
I've tried this:
<div ng-show="someDynamicArrayOfValues">
<select ng-model="mySelectedValue" ng-options="arrayValue for arrayValue in someDynamicArrayOfValues" ng-selected="myFunctionForDeterminingWhetherValueIsSelected(arrayValue)">
<option value="">--</option>
</select>
</div>
and this:
<div ng-show="someDynamicArrayOfValues">
<select ng-model="mySelectedValue" ng-options="arrayValue for arrayValue in someDynamicArrayOfValues" ng-init="myFunctionForSettingSelectedValue()">
<option value="">--</option>
</select>
</div>
but neither of those work because the select is built (and ng-init and ng-selected both get evaluated) before someDynamicArrayOfValues has been set and, therefore, before the <select> is even visible. When using <option ng-repeat="...">, the <select> doesn't get built/initialized until after someDynamicArrayOfValues is set, which is why I had been going that direction.
Is there a way to get the ng-options technique to work while, at the same time, having the select dependent on someDynamicArrayOfValues (if ng-options is the better way to go)?
UPDATE 2:
Here's a Plunker (modified from ababashka's answer) that is a little closer to what I'm ultimately trying to achieve: http://plnkr.co/edit/Kj4xalhI28i5IU0hGBLL?p=preview. It's not quite there yet... I'd like it to have each of the 3 dropdowns set with the closest-matching dynamic value once someDynamicArrayOfValues is set.
I think that it will be good it you will use ng-options attribute of select tag. It's an angular directive which creates options according to Array of options. You can take a look at select documentation
If you use your code - your function myFunctionForDeterminingWhetherValueIsSelected works twice for every option at initialization and once for every option item when you select some another option.
Demo with your code: http://plnkr.co/edit/0IVNLHiw3jpz4zMKcB0P?p=preview
Demo for select you could see at description of select directive.
Update
At first, to see when value is changed - you need to use ng-change attribute of select tag, like this:
<select ng-model="mySelectedValue"
ng-options="myValue for myValue in someDynamicArrayOfValues"
ng-change="myFunctionForDeterminingWhetherValueIsSelected()">
<option value="">--</option>
</select>
Then, i don't know how does myFunctionForSettingSelectedValue look like, but there are 2 variants:
This function returns some value - then you need to use ng-init next way.
Controller:
$scope.someInitFunc = function () {
return 'One';
};
HTML:
<select ng-model="mySelectedValue"
ng-options="myValue for myValue in someDynamicArrayOfValues"
ng-change="myFunctionForDeterminingWhetherValueIsSelected()"
ng-init="mySelectedValue = someInitFunc()">
<option value="">--</option>
</select>
You set value of mySelectedValue in this function - then you do this.
Controller:
$scope.someInitFunc = function () {
$scope.mySelectedValue = 'One';
};
HTML:
<select ng-model="mySelectedValue"
ng-options="myValue for myValue in someDynamicArrayOfValues"
ng-change="myFunctionForDeterminingWhetherValueIsSelected()"
ng-init="someInitFunc()">
<option value="">--</option>
</select>
I have created an example which implements the first version of using ng-init. When new value is selected - it's printed to console.
Also, i moved options to the options.json file. So options are initialized just after ajax request was finished. Everything works great.
Demo: http://plnkr.co/edit/pzjxxTnboKJXJYBGcgNb?p=preview
Update 2
Hello again. I think you don't need to have any ng-init according to your requirements. You can just initiate values of your model when http request is finished. Also i don't understand why do you need ng-change function in this case.
Here is modified code you need from your plunk where values of ng-models are initiated after options are loaded.
JavaScript:
.controller('MainCtrl', function($scope, $http) {
$scope.someStaticArrayOfValues = ['One', 'Two', 'Three'];
$scope.mySelectedValues = {};
$http.get('options.json').then(
function (response) {
$scope.someDynamicArrayOfValues = response.data;
for (var i = 0; i < $scope.someStaticArrayOfValues.length; ++i) {
$scope.someDynamicArrayOfValues.some(function (value) {
if (value.substring(0, $scope.someStaticArrayOfValues[i].length) === $scope.someStaticArrayOfValues[i]) {
$scope.mySelectedValues[$scope.someStaticArrayOfValues[i]] = value;
return true;
}
});
}
},
function (response) {
console.log('ERROR!');
}
);
});
HTML:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-show="someDynamicArrayOfValues">
<ul>
<li ng-repeat="staticValue in someStaticArrayOfValues">
{{staticValue}} -
<select ng-model="mySelectedValues[staticValue]"
ng-options="myValue for myValue in someDynamicArrayOfValues">
<option value="">--</option>
</select>
<h2>{{mySelectedValues[staticValue]}}</h2>
</li>
</ul>
</div>
</body>
Demo: http://plnkr.co/edit/9Q1MH0esGE1SIJa0m2NV?p=preview
Here is a modified plunker that works as intended: http://plnkr.co/edit/Y8OSvmrG3u0XjnCU3ah5?p=preview.
The main change was using ng-if in place of ng-show. This forces angular to recompile/link the html whenever it is rendered:
<div ng-if="someDynamicArrayOfValues">
...
</div>
Also ng-change, from the original plunker, shouldn't be necessary, and there were a couple of typos fixed.
It works a whole lot better when you use ng-options on your select element instead of nesting option with ng-repeat.
https://docs.angularjs.org/api/ng/directive/select
Then you are capable of setting the ng-model with ng-init.
You can try to set the initial value of mySelectedValue in your Controller like so:
$scope.mySelectedValue = '';
I have created example for your problem in plnkr.
Visit: plnkr.co/edit/rKyjijGWSL1IKy51b8Tv?p=preview
You are going about it the reverse way. ng-model reflects the state of the <select> and is two-way bound.
You just need to set your mySelectedValue to what you want <select> to select first, and no other tricks are required.
So, in the controller, do something like the following:
$scope.mySelectedValue = someDynamicArrayOfValues[0];
And remove the ng-selected and the <option ng-repeat...> from <select>:
<select ng-model="mySelectedValue"
ng-options="value for value in someDynamicArrayOfValues">
<option value="">--</option>
</select>

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