How to assign a second parameter value on ng-change in angularjs? - javascript

I have simple drop-down bind with angular model
<select
ng-model="user.Id"
ng-options="convertToInt(c.Id) as c.Name for c in users"
ng-change="changeItem(user.Id)"
>
<option ng-selected="c.Id == user.Id" value="{{c.Name}}"></option>
</select>
and in controller
$scope.changeItem = function(item){
//userid
}
How can I get User name from the select box, ie return c.Name?

Pass the Alice object
ng-change="changeItem(c)"
and then,
$scope.changeItem = function(user){
console.log(user.name);
}

Pass the whole user object
ng-change="changeItem(c)"
and then,
$scope.changeItem = function(item){
console.log(item.name);
}

What about
<selectng-model="user"
ng-options="item as item.name for item in users track by item.id"
ng-change="onChange()">
</select>
$scope.onChange = function(){
console.log($scope.user);
};
Working demo

Select the entire object to a selectedUser and you can get what ever you want out of the object.
<div ng-app="myApp" ng-controller="HomeCtrl as vm">
<select ng-options="user as user.name for user in vm.users" ng-model="vm.selectedUser"></select>
<p>Selected user: {{vm.selectedUser.name}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
angular.module('myApp', [])
.controller('HomeCtrl', function() {
let vm = this;
vm.users = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Joe',
},
{
id: 3,
name: 'Jim',
},
];
vm.userId = 2;
vm.selectedUser = vm.users.find(u => u.id === vm.userId);
});
</script>

Related

How to preselect a specific element from dropdown using ng-repeat

This is my html code:
<select id="selectFileType" ng-model="instance.fileType" required>
<option ng-repeat="(key, value) in fileTypes" id="key" value="{{key}}">{{key}} ({{value}})</option>
</select>
I am using a map of items to fill the list with information - now I want to pre-select a specific element based on the key but all the solutions I found didn`t work.
E.g. I tried to use the id field to use something like:
document.getElementById("A").selected = true;
Does someone have an idea what I should do?
Thanks and have a nice day
Use the ng-selected directive to set your pre-selected option.
angular.module('myApp', [])
.controller('ctrl', function($scope) {
$scope.vm = {
priceTypes: [{
id: 3,
name: 'pound'
},
{
id: 5,
name: 'Yen'
},
{
id: 6,
name: 'dollar'
}
]
};
//select model value
$scope.localModel = {
priceType: $scope.vm.priceTypes[1]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes as item"
ng-selected="localModel.priceType.id == item.id"
value="{{item}}"
>{{item.name}}</option>
</select>
<div>
priceType: {{ localModel.priceType }}
</div>
</div>

Handling dropdown in angular js

I have a dropdown with some values :
Apple
Mango
Orange
Grapes
HTML :
<div class="form-group">
<label class="control-label col-sm-20" for="groupz">Role*</label>
<select class="form-control" ng-model="model.selectedRole" name="role" ng-change="GetRole(model.selectedRole)" >
<option value class selected>Select Roles</option>
<option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
I want my $scope.selectedRole to be by default as Apple. But later when the user needs to change the value, they can change it from apple to orange or any other fruit name. I have separate service request to fetch the fruits from backend and I write my code in controller as follows.
$scope.GetRole = function() {
$scope.selectedrole = [];
if ($scope.model.selectedRole != null) {
for (var i = 0; i < 1; i++) {
$scope.selectedrole.push($scope.model.selectedRole);
}
}
}
I hope this helps you
JsFiddle
In js
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.selectedrole = ['Apple', 'Mango', 'Orange', 'Grapes'];
$scope.selectRole= $scope.selectedrole[0];
});
In HTML
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectRole" ng-options="role for role in selectedrole">
</select>
</div>
just try : HTML
<select class="form-control select" name="role" id="role" data-ng-model="ctrl.model.selectedRole" data-ng-options="option.name for option in ctrl.model.roles track by option.id"></select>
in your contoller
$scope.model = {
roles: [{
id: '1',
name: 'Apple'
}, {
id: '2',
name: 'Orange'
}, {
id: '3',
name: 'Mango'
}],
selectedRole: {
id: '1',
name: 'Apple'
} //This sets the default value of the select in the ui
};
Then assign the first array element to selectedrole containing the array of values(Apple Mango Orange Grapes).
If you want the default to be apple and the array is ordered:
array = [Apple, Mango, Orange, Grapes]
Your model needs to be set to selectedRole:
data-ng-model="selectedRole"
In your controller, set:
selectedRole = array[0]
angular will take care of the rest of the data manipulation.
I hope this helps. Please provide more information for a clearer answer
Thanks
Handling a select element i.e. a drop down list in AngularJS is pretty simple.
Things you need to know is that you bind it to an array or a collection to generate the set of option tags using the ng-options or the ng-repeat directives which is bound to the data source on your $scope and you have a selected option which you need to retrieve as it is the one the user selects, it can be done using the ng-model directive.
If you want to set the selected option on the page load event, then you have to set the appropriate object or value (here it is the fruit id) which you are retrieving from data binding using the as clause in the ng-options directive as shown in the below embedded code snippet
ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
or set it to the value of the value attribute when using the ng-repeat directive on the option tag i.e. set data.model to the appropriate option.value
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
angular
.module('fruits', [])
.controller('FruitController', FruitController);
function FruitController() {
var vm = this;
var fruitInfo = getFruits();
vm.fruits = fruitInfo.fruits;
vm.selectedFruitId = fruitInfo.selectedFruitId;
vm.onFruitChanged = onFruitChanged;
function getFruits() {
// get fruits and selectedFruitId from api here
var fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Mango' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Orange' }
];
var fruitInfo = {
fruits: fruits,
selectedFruitId: 1
};
return fruitInfo;
}
function onFruitChanged(fruitId) {
// do something when fruit changes
console.log(fruitId);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fruits">
<div ng-controller="FruitController as ctrl">
<select ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
ng-model="ctrl.selectedFruitId"
ng-change="ctrl.onFruitChanged(ctrl.selectedFruitId)">
<option value="">Select Fruit</option>
</select>
</div>
</div>
Check the Example section here for more information.

Angular Default Value in Server Supplied Dropdownlist

I have a dropdownlist of U.S. States which is populated from a call to our web api. I have an edit page that fills in a user's details and I need to bind that dropdownlist to the state in the user's information. I'm sure this has something to do with ng-options, but I do not know how to implement it.
Here is my HTML for the dropdownlist:
<select data-ng-model="form.vchOfficeStateVchID" ng-options="s as s.StateVchID for s in userdetails.vchOfficeStateVchID" style="height:25px">
<option value="">--Select State--</option>
<option ng-repeat="state in states" value="state.StateVchID">{{state.StateVchID}}</option>
</select>
The function in my controller that populates the dropdownlist is:
getStates();
function getStates() {
operatorService.getallstates()
.success(function (data) {
$scope.states = data;
});
};
It returns an array which has the state abbreviation as its key "StateVchID" (I didn't create this database).
The user info is returned in the controller with the following function:
$scope.showDetails = function (user) {
$scope.noUser = false;
var userid = user.UserID;
operatorService.getuserdetails(userid)
.success(function (data) {
$scope.userdetails = data;
$scope.form.vchOfficeStateVchID = userdetails.vchOfficeStateVchID;
$scope.form.vchOfficeCountryVchID = userdetails.vchOfficeCountryVchID;
});
$scope.viewUser = true;
};
In the user's details, the State Abbreviation is held in the vchOfficeStateVchID field.
How do I get my dropdownlist to display the user's correct state? Basically, I need state.StateVchID = userdetails.vchOfficeStateVchID.
Any assistance is greatly appreciated!
Have a look at this example:
HTML
<div ng-app="myApp" ng-controller="myController">
<select name="vchOfficeStateVchID" ng-model="form.vchOfficeStateVchID" ng-options="s.StateVchID as s.Name for s in states">
<option value="">--Select State--</option>
</select>
<br/>
<div>
<h3>
Selected ID:
</h3>
{{form.vchOfficeStateVchID}}
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope){
$scope.userdetails = {
vchOfficeStateVchID: 3
}
$scope.form = {};
$scope.states = [
{
Name: "New York",
StateVchID: 1
},
{
Name: "Texas",
StateVchID: 2
},
{
Name: "Las Vegas",
StateVchID: 3
},
{
Name: "Hawaii",
StateVchID: 4
}
];
$scope.form.vchOfficeStateVchID = $scope.userdetails.vchOfficeStateVchID;
}]);

Angular change default value of select from filter

I have a select box which is populated with some data from my controller. When an input value changes the contents of the select box should be filtered and a default value should be assigned based on the is default property of the data object.
Is there any way this can be done using angular directives or would it need to be done as a custom filter function doing something along the lines of
angular.forEach(vm.data,function(item){
if (vm.q == item.someId && item.isDefault) {
vm.result = item.value;
}
});
My html looks something like
<div ng-app="myApp" ng-controller="ctrl as vm">
<input type="text" ng-model="vm.q">
<select ng-options="item.value as item.description for item in vm.data | filter:{someId:vm.q}" ng-model="vm.result"></select>
</div>
and my controller looks like:
(function(){
angular.module('myApp',[]);
angular
.module('myApp')
.controller('ctrl',ctrl);
function ctrl()
{
var vm = this;
vm.data = [
{
someId: '1',
description: 'test1',
value: 100,
isDefault: true
},
{
someId: '2',
description: 'test2',
value: 200,
isDefault: false
},
{
someId: '3',
description: 'test3',
value: 100,
isDefault: true
},
];
}
})();
See my plunkr demo here: http://plnkr.co/edit/RDhQWQcHFMQJvwOyHI4r?p=preview
Desired behaviour:
1) Enter 1 into text box
2) List should be filtered to 2 items
3) Select box should pre-select item 1 based on property isDefault set to true
Thanks in advance
I'd suggest you include some 3rd party library, like lodash, into your project to make working with arrays/collections that much easier.
After that you could add ng-change directive for your input.
<input type="text" ng-model="vm.q" ng-change="vm.onChange(vm.q)">
And the actual onChange function in the controller
vm.onChange = function(id) {
var item = _.findWhere(vm.data, { someId: id, isDefault: true });
vm.result = item ? item.value : null;
};
And there you have it.

Filtering an ng-repeat based on multiple values in angular

This is difficult to phrase but:
I have 1 collection called users.
Every user has 3 properies: id, name, skill.
{
_id: 1,
name: 'frank young',
skill: 'java'
},
I have 1 form collects search results upon pressing enter.
<form ng-submit="pushToNewArry(searchTerm)">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
this is not the best way to do this
$scope.newUsers = [];
$scope.pushToNewArry = function(msg) {
$scope.trackedUsers.push(msg);
$scope.searchTerm = '';
};
Question:
How do I create a filter that will run over multiple search terms and create a list proper matches based on the users collections vs inputed values.
<ol ng-repeat = "user in users | filter: trackedUsers">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
Upon submission, the user input will be saved and create a new array of users based on inputed values of search. therefore, multiple matching values.
Updated:
JSFiddle
not excatly the same as example above because I keep playing with it.
You mean like this jsfriddle
updated fiddle
updated fiddle2
<div>{{listSearchTerms | json}}</div>
<form ng-submit="saveSearchTerm()">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
<ol ng-repeat = "user in users | filter:filterSearch(searchTerm)">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
Javascript
var app = angular.module('app', []);
//App.directive('myDirective', function() {});
//App.factory('myService', function() {});
app.controller('MainCtrl', function ($scope) {
$scope.users = [
{
_id: 1,
name: 'frank young',
skill: 'java'
},
{
name: 'jeff qua',
skill: 'javascript'
},
{
name: 'frank yang',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'javascript'
},
];
$scope.searchTerm = "";
$scope.listSearchTerms = [];
$scope.filterSearch = function (terms) {
return function (item) {
return terms.length < 1 ? true :
terms.reduce(function (lastresult, term) {
return lastresult + (item.name.indexOf(term) > -1 || item.skill.indexOf(term) > -1);
}, 0) > 0;
}
};
$scope.saveSearchTerm = function () {
$scope.listSearchTerms.push($scope.searchTerm);
$scope.searchTerm = "";
}
});

Categories

Resources