Set value of multiple dropdowns - angularjs

I am trying to set the value of many select elements when a user presses a button.
I have tried the jQuery way:
vm.passAllInspections = function ($event) {
$(".tbl-inspections option[value=pass]").attr("selected", "selected");
console.log($event);
}
This works but does not update ng-model or even make it fire. I looked at this post which gives details on the input element. I could not get the trigger event to happen?
$('button').click(function(){
var input = $('input');
input.val('xxx');
input.trigger('input');
});
So then I tried to use the $compile directive $compile(vm)($scope); that doesn't work as I wasn't sure if it had to be the exact ng-model property?
Then I was looking at useing ng-click="vm.eicr.inspections='pass'" but wasn't sure how to apply it to every ng-model property.
How can I press a button and add pass to a list of dropdowns and fire the ng-model so the properties are all set.

You have your listbox:
<select data-ng-model="myValue">
<option value="1">value 1 </option>
<option value="2">value 2 </option>
<option value="3">value 3 </option>
</select>
You have a button:
<button data-ng-click="setListboxToValue('2')" value="Click me!"/>
When you click the button, you trigger this function:
$scope.setListboxToValue = function(value) {
$scope.myValue = value;
}
This will set your listbox to the value you want.
Full example code: jsFiddle

Related

angular ng-model is not working as expected

Template:
<select id="siteOptions" ng-model="siteVal" ng-change="siteChange()">
<option ng-repeat = "site in sites" ng-selected="{{site == selectedSite}}" value="site">{{site}}</option>
</select>
Controller:
$scope.siteChange = function(){
console.log(" $scope.siteVal--> "+ $scope.siteVal);
}
I could able to populate values in dropdown properly, but when I try to select value in dropdown I could see "$scope.siteVal--> undefined".
Even when I select the dropdown value multiple time ng-change is triggering only once.
Remove .value attribute from your html markup and your code would work fine!
<select id="siteOptions" ng-model="siteVal" ng-change="siteChange()">
<option ng-repeat = "site in sites" ng-selected="{{site == selectedSite}}">{{site}}</option>
</select>
From the DOCS
Note: ngSelected does not interact with the select and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected option
Here is the plunker which demonstrates the same

get object from datalist ng-repeat angular

I got datalist such as below ,and color a color object with name and id properties.
<datalist id="opts">
<option ng-repeat="color in colors" value = "{{color.id}}">color.name</option>
</datalist>
My problem is that i want to run a function with the id and the name of the selected color. how can i access both of them without show the id on the view?
<button ng-click="someFunction(color.id,color.name)">button </button>
You should do it manually, as ng-options directive would be good option to go, but unfortunately it doesn't supported for datalist. To get selected value inside controller scope you need to add ng-model to datalist
Markup
<datalist id="opts" ng-model="selectedColor">
<option ng-repeat="color in colors" value = "{{color.id}}">color.name</option>
</datalist>
<button ng-click="someFunction(selectedColor)">button</button>
And then do filter on color collection inside controller someFunction
$scope.someFunction = function(){
var selected = $filter('filter')($scope.colors, {id: parseInt(selectedColor)}, true),
selectedColor;
if(selected){
selectedColor = selected[0];
}
}
Use Angular Expression to Bind {{color.name}} in option or use Value attribute
<option ng-repeat="color in colors" value = "{{color.id}}" ng-change="someFunction(color )">{{color.name}}</option>
You can also give a try to use ng-change in side the datalist
Example:
<datalist id="opts">
<option ng-repeat="color in colors" value = "{{color.id}}" ng-change="someFunction(color )">{{color.name}}</option>
</datalist>
Now With in the Function You can Access both the id and name...For this No need of submit button
$scope.someFunction = function(colorobj){
var colorid=colorobj.id;
var colorname=colorobj.name;
}
You can do as illustrated below.
Pass directly the object - 'color' and access the 'id', 'name', etc in the controller.
HTML:
<button ng-click="someFunction(color)">button </button>
JS:
$scope.someFunction = function (colorObj) {
// access colorObj.id, colorObj.name, etc.
}

Call method on selecting an option

I want to call specific methods based on which option was clicked, like this:
<select>
<option value="0" ng-click="callMethodOne()">1</option>
<option value="1" ng-click="callMethodTwo()">2</option>
</select>
But it doesn't work, I can't call ng-click inside the option tag.
I also can't use it inside the select tag because I won't be able to call the function by its name.
How could I solve this?
You need to add ng-change config along with ng-model on <select> tag.
<select ng-model="selectedOption" ng-change="onChange">
<option value="0">1</option>
<option value="1">2</option>
</select>
Now, In your controller, define onChange function as
$scope.onChange = function(){
// The option selected is stored in $scope.selectedOption
// perform the business logic using $scope.selectedOption
}

AngularJS - Dropdown doesn't show selected option

I have this select dropdown with "Enbridge Billing" selected.
<select class="form-control required ng-pristine ng-valid" ng-model="finance.payment_method" id="payment_method" name="payment_method">
<option value=""></option>
<option value="EGD" selected="selected">Enbridge Billing</option>
<option value="PAPP">PAD Billing</option>
</select>
However, on screen, it's not selected:
I've removed all the stuff from app.js and still the problem presists:
var app = angular.module('portal', []);
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('%%');
$interpolateProvider.endSymbol('%%');
});
app.controller('NewJobFinanceController',
function ($scope) {
});
Edit:
I just did this in the controller:
$scope.finance.payment_method = $('#payment_method').find(':selected').val();
The single point of truth in angular is the model. Not the view. You update the model, and the view updates itself to reflect the state of the model.
You configured the select box as
<select ng-model="finance.payment_method" ...>
So that means that the currently selected value is finance.payment_method. That's where angular gets the selected value. Since it's undefined, you have a blank select box.
BTW, you should not set, required, ng-pristine and ng-valid as class of your select box. angular will add and remove this classes by itself, depending on the actual state of the form control.
Simply use ng-selected="true" instead of selected="selected".

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>

Resources