How do I set a selected option for select in Angular - angularjs

I have an object
$scope.colleges = [{"CollegeCode":"40","CollegeName":"College1"},
{"CollegeCode":"35","CollegeName":"College2"},
{"CollegeCode":"32","CollegeName":"College3"},
{"CollegeCode":"15","CollegeName":"College4"}]
I'm populating a select element with it's contents
<select ng-model="collegeSelection" ng-options="c as c.CollegeName for c in colleges" name="selectCollege"></select>
It renders on the page like so
<select class="ng-pristine ng-valid" name="selectCollege" ng-options="c as c.CollegeName for c in colleges" ng-model="collegeSelection" style="" selected="selected">
<option value="?" selected="selected"></option>
<option value="0">College1</option>
<option value="1">College2</option>
<option value="2">College3</option>
<option value="3">College4</option>
etc....
I'm also binding this select to collegeSelection and when an item is selected the object look like this
$scope.collegeSelection = {"CollegeCode":"32","CollegeName":"College"}
When someone clicks edit on the page, the college I want selected by default comes from the userToUpdate object.
$scope.userToUpdate = {
Id: 1,
FirstName: 'John',
LastName: 'Doe',
CollegeCode: '35,
CollegeName: 'College2',
Active: true
};
When an edit button and the userToUpdate object is populated, I would like the college in the select element to be set to the college in the user object. How could one make this happen? FYI, the value in the rendered select does not match the CollegeCode. It seems angular uses the index from the colleges object. Thanks

Try this one
<select ng-model="collegeSelection" ng-options="c.CollegeCode as c.CollegeName for c in colleges" name="selectCollege"></select>
<span>{{collegeSelection}}</span>
<input type="button" ng-click="switch()" name="switch" value="switch" />
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $filter) {
$scope.colleges = [{ "CollegeCode": "40", "CollegeName": "College1" },
{ "CollegeCode": "35", "CollegeName": "College2" },
{ "CollegeCode": "32", "CollegeName": "College3" },
{ "CollegeCode": "15", "CollegeName": "College4" }
]
$scope.switch = function () {
$scope.collegeSelection = "32";
};
});

Related

angular ui-select2 not set value in edit mode

<select id="e1" style="width:100%" ui-select2 tabindex="-1" ng-init="GetAllAgent()" ng-model="Agent" ng-options="ctr as ctr.AgentName for ctr in ListAgent track by ctr.AgentId" ng-change="GetSubAgentList(Agent.AgentId)">
<option value=""> </option></select>
when it is in edit mode,could not set the default value using the below code
angular.forEach($scope.ListAgent, function (value, index) {
if (value.AgentId == HR.AgentId) {
$scope.Agent = $scope.ListAgent[index];
}
})
$scope.ListAgent= [{ AgentId: "0", AgentName:"Ann" }, { AgentId: "1", AgentName:"Muh" }];
and
HR.AgentId=1
First off, ui-select2 does not support ng-options: https://github.com/angular-ui/ui-select2/issues/252
Further, ui-select2 does not work with ng-repeat: https://github.com/angular-ui/ui-select2/issues/162
The solution is to use input:
<input ui-select2="select2Options" ng-model="Agent"/>
where select2Options is:
$scope.select2Options = {
data:$scope.ListAgent
}
The list should have structure: [{id,text}] so $scope.ListAgent will be
$scope.ListAgent= [{ id:0, text:"Ann" }, { id:1, text:"Muh" }];
Demo Plunker
For place holder add data-placeholder="----"

How to make my first element in datalist filtered result , to be selected automatically

The following is my code:
<input required class="input form-control" type="text" ng-model="select.mySelect" list="bloodgroups" placeholder="Select Blood Group">
<datalist id="bloodgroups" >
<option ng-repeat="bloodgroup in bloodgroups"> {{bloodgroup.bloodgroups}}
</datalist>
JS
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
Additional example:
This is in the case of retrieving data (GET) from an external source (url). Something.thisismydata is from factory.
For ng-model="select.mySelect" something like this:
$scope.showDataOnSelect = function() {
var url = "http://example.com/api";
Something.thisismydata(function(data) {
$scope.thisismydata = data;
$scope.select.mySelect = $scope.thisismydata[0].id;
}, url);
}
$scope.showDataOnSelect();

setting first item as selected for hash type

Using angularjs while creating a select element, I can set the first value as selected using
ng-init="item.state = stateArray[0]"
How to set the first item selected for key/value type array?
var States = { "AL": "Alabama", "AK": "Alaska", "AZ": "Arizona" }
html code:
<select ng-model="item.state" ng-options="k as v for (k,v) in States" class="form-control"></select>
I also tried
ng-init="item.state = Object.keys(States)[0]"
For ng-options:
Demo: http://jsfiddle.net/U3pVM/17821/
HTML:
<select ng-init="o = getFirst();" ng-model="o" ng-options="k as v for (k,v) in States" class="form-control"></select>
JS:
$scope.States = {
"AL": "Alabama",
"AK": "Alaska",
"AZ": "Arizona"
};
$scope.getFirst = function () {
var v = Object.keys($scope.States)[0];
return v;
};
For ng-repeat:
You can use $first for selecting the first option in case of ng-repeat.
ng-selected="$first?'selected':''"
try this
ng-init="item.state= stateArray['AL']"
Try this way.
In your controller,
$scope.States = { "AL": "Alabama", "AK": "Alaska", "AZ": "Arizona" };
var arrProp = Object.getOwnPropertyNames($scope.States);
$scope.item = {};
$scope.item.state = arrProp[0];
And HTML as it is,
<select ng-model="item.state" ng-options="k as v for (k,v) in States" class="form-control">
<option value="">Select </option>
</select>

How to insert dynamically a text in an object "angular"?

I would like to be able to select a specific object and enter a text in it 'dynamically' in Angular.
App file:
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", ["$scope", function($scope){
$scope.persons = [
{
name: "Kevin",
lastName: "Cris",
mottos : [
{
motto: "Holy Moly!"
}
],
},
{
name: "Tres",
lastName: "Yepo",
mottos : [
{
motto: "Crispy!"
}
],
},
{
name: "Prosi",
lastName: "Nani",
mottos : [
{
motto: "I love this!"
}
],
}
];
}]);
I can insert a text in the object in array[1]:
$scope.addMotto = function(){
$scope.persons[1].mottos.push({
motto: $scope.enterMotto
});
};
But, how could I be able to add motto to a person object each time?
To be more clear: What I am trying to do is: Select a person and add motto.
What I can't figure out is: How to create selection of a person object and add on selected object a text.
Html file:
<div ng-controller="myCtrl">
<section ng-repeat="person in persons">
<p class="header">Persons --</p>
<p>Name: {{person.name}}</p>
<p>lastName: {{person.lastName}}</p>
<p ng-repeat="shoutOut in person.mottos" class="motto">Motto: {{shoutOut.motto}} </p>
</section>
<p ng-repet="newMotto in persons.mottos">Your Motto: {{newMotto.motto}} </p>
<p>Enter Motto:<input type="text" ng-model="enterMotto" /></p>
<button ng-click="addMotto()">Submit </button>
</div><!--myCtrl-->
Live: http://jsfiddle.net/9eau9dq2/
If you want to add to each of the person object, here is what you should do - http://jsfiddle.net/k8o8x60w/
$scope.addMotto = function(){
angular.forEach($scope.persons, function(item, i){
item.mottos.push({motto: $scope.enterMotto});
});
};
If you want to add to the selected person object, you will need to keep the selected id with you and update the id whenever a different person is selected and update his motto accordingly.
You could provide a select box like this to allow user to select a person to which you would want to add a motto
<select>
<option ng-repeat="person in persons" value="{{person.name}}">{{ person.name }} {{ person.lastName }}</option>
</select>
and update your method to...
$scope.addMotto = function () {
angular.forEach($scope.persons, function (item, i) {
if (item.name == $scope.selectedperson) {
item.mottos.push({
motto: $scope.enterMotto
});
}
});
};
Updated fiddle : http://jsfiddle.net/k8o8x60w/1/
Note: Would strongly advice you to use some id too in the person object.
i updated your fiddle with some working code!
http://jsfiddle.net/9eau9dq2/1/
You could also use a select box for sure, but that is really similar anyways ;-)
Hope that helps!
Jan

How can I set the initial value of a <select> with AngularJS?

I am using this code in my controller:
$scope.$watch('option.selectedPageType', function () {
if ($scope.isNumber($scope.option.selectedPageType)) {
localStorageService.add('selectedPageType', $scope.option.selectedPageType);
}
})
getPageTypes: function ($scope) {
$scope.option.pageTypes = [
{ id: 0, type: 'Edit Basic' },
{ id: 1, type: 'Edit Standard' },
{ id: 2, type: 'Report' }
];
$scope.option.selectedPageType = parseInt(localStorageService.get('selectedPageType'));
},
and in my HTML:
<select data-ng-model="option.selectedPageType"
data-ng-options="item.id as item.type for item in option.pageTypes">
<option style="display: none" value="">Select Page Type</option>
</select>
Instead of using the "Select Page Type" option. How can I make it so my code defaults to the value in local storage or if there is nothing there then to one of the values I have in my option.pageTypes list ?
Have your localStorageService return null if there is nothing stored. If it does exist, have the service return the integer
Then in controller:
/* assume want first item in array */
$scope.option.selectedPageType = localStorageService.get('selectedPageType') || $scope.option.pageTypes[0].id
Try using ng-init on the <select ...>:
<select data-ng-model="option.selectedPageType"
data-ng-options="item.id as item.type for item in option.pageTypes"
data-ng-init="option.selectedPageType=DEFAULT_VALUE">
See this fiddle: http://jsfiddle.net/CaeUs/5/

Resources