How to add boolean attributes to directive? - javascript

In HTML, there are attributes like the selected attribute:
<option selected>This option is selected</option>
It's either present or not present, which translates to on/off (Boolean).
I can't find a way to create an attribute like this for an AngularJs directive. Is there any way?
An example would be:
<modal ng-show="modal.show" with-backdrop> // "with-backdrop" is a boolean attribute.

I read again your question and i was wrong. To archieve what you want, you should do the next:
HTML Element:
<modal id="myModal" ng-show="modal.show" with-backdrop>
And in your controller:
function somethingController() {
var modalElement = document.querySelector('#myModal');
// If you want to check that element have your attribute.
var isMyAttributeSet = modalElement.getAttribute('with-backdrop') !== null;
// If you want to set up the attribute.
modalElement.setAttribute('with-backdrop', '');
}
The setAttribute method requires 2 arguments (attributeName, attributeValue), but if you pass an empty string as second parameter, the attribute would be seen as you want, i have tested it in chrome console :)

It's going to be different depending on what you're doing. In your example, you want to know which option is selected. That would be found by checking the model for the <select> to see what's in it. For example:
<select data-ng-model="user.defaultThing"
data-ng-options="thing.id as thing.name for thing in thingCollection">
<option value="">None</option>
</select>
With this setup, any time the selection is changed, the thing.id is stored in user.defaultThing.
NB: The 'None' option I have there, allows for a null selection.
Now, if you were looking to see if a checkbox is checked, it's similar as you'd just see what's in the model it's tied to.
<input type="checkbox" data-ng-model="form.someOption">
When you go to process the form, just see if form.someOption is true or false.

Related

How to get the value in a select change event in angular2

I want to navigate useing a dynamically generated select drop down.
It doesn't appear I can do that directly, so I'd simply like to make a function call when the select changes.
To do that, I have this:
---In the template---
<select (change)="navSelected($event)">
<option *ngFor="let button of navButtons;"
value="button.route" >{{button.label}}</option>
</select>
suffice it to say that 'navButtons' is an array of objects that have a 'label' field.
---In the class---
navSelected(navName) {
console.log(navName + " Clicked!");
}
This actually works fine.
I got to this point from the great help of Mark Rajcok and his answer in this older question:
How can I get new selection in "select" in Angular 2?
That said, I'd like to be able to pass the selected value in the navSelected() function call. I'm unsure how to do that.
I have tried adding [ngValue]="button" on a wild guess from other searches to the option tag and then referencing the button variable in the (change) event handler (so: (change)="navSelected(button.label)" and other combos, to no avail. I've seen a lot of references to ngModel but they seem old and I'm not entirely sure they apply anymore (and I couldn't get them to work anyway in RC4).
I could probably pull some jquery or whatever out to find the select and get it's value, but that seems very rinky-dink compared to simply being able to call the function correctly.
The value you are looking for is on the $event.target and you can get it with $event.target.value, see my example below.
navSelected($event) {
console.log($event.target.value + " Clicked!");
}
If you are looking to get the selected text of the option you can do this
navSelected($event) {
let selectElement = $event.target;
var optionIndex = selectElement.selectedIndex;
var optionText = selectElement.options[optionIndex];
console.log(optionText + " Clicked!");
}
As a shortcut for #eltonkamami 's answer, you can pass your object like this:
<select (change)="navSelected(navButtons[$event.target.selectedIndex])">
<option *ngFor="let button of navButtons;">{{button.label}}</option>
</select>
And capture it like this:
navSelected(button: [type of navButtons]){
console.log(button);
}
Instead of $event. Try using the below typecast function.
$any($event.target).value
Which will stop the type checking in the template.

JavaScript object value modification

I'm using JavaScript (Google Apps Script to be precise) and I'm having some trouble with objects.
I have a var, formData, which is full of data passed back from an HTML form. I can happily access the values like this; exhibitions is the name of a select element;
formData.exhibitions.value
But I want to change the value from "*" to "ALL". I have tried all the following;
formData.exhibitions.value = "ALL"
formData["exhibitions"] = "ALL"
formData.element["exhibitons"] = "ALL"
and a few other versions of the above but nothing alters the value.
edit- cut down code, HTML form
<form>
Exhibition search <select id="exhibitionList" name ="exhibition">
<option value="*">All</option>
<option value="shoes">shoes</option>
</select>
<input type = "button" value ="Item Search" onclick="printSearch(this.form)"/>
</form>
and the function is
printSearch(formData){
if(formData.exhibition.value != "*"){
whereData.push(exhibition+"='"+formData.exhibition.value+"'");
}else{formData.set('exhibition','ALL');}
}
everything works fine I just can't seem to change the value past the ELSE statement.
What you're trying to do can't work. The value of a <select> has to be the value of one of its <option> elements. This is because the value is actually stored in the select's selectedIndex property. When you assign to formData.exhibition.value, it searches the options for one whose value matches this, and then sets formData.exhibition.selectedIndex to its position. If there's no match, it fails and doesn't change the value.
Since you have no <option value="ALL"> element, trying to set the value to that must fail.

jQuery Autopopulate Multiple Select uses text instead of value

I've got a multiple select like this configured to auto-populate:
<select id="multiple-select-box" class="selectivity-input" data-placeholder="Type to search condos" multiple>
<option id="Alabama Grove Terrace" value="Alabama Grove" >Alabama Grove Terrace</option>
<option id="Alden Pines" value="Alden Pines" >Alden</option>
</select>
Upon select I realized the script is submitting the visible Text for each option instead of the value="" for each option chosen.
I tried to change var t=$(this).text(); to var t=$(this).value(); thinking that would grab the value instead of the option text but had the same results. What am I missing?
<script>
$(document).ready(function() {
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).text();
//if()
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
})
$('#multiple-select-box').selectivity();
});
</script>
Ok, so I went to check this selectivity plugin you're using and it converts your select into a series of divs as
<div class="selectivity-results-container">
<div class="selectivity-result-item highlight" data-item-id="Alabama Grove">Alabama Grove Terrace</div>
<div class="selectivity-result-item" data-item-id="Alden Pines">Alden</div>
</div>
you have to change your submit function to get the data-item-id property which corresponds to your original select value like
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).data("item-id");
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
edit
fiddle example
In this line, you are appending options to the select, but you have set no value attribute:
$(".ml").append("<option selected='selected'>"+t+"</option>");
As stated in the comments, the "fetch value" method of a form element in jQuery is:
$(this).val()
You might be confusing it with the JavaScript property:
this.value
...which also works. Both return an array of strings if something is selected and set to "multiple"
To follow up on your comment, I don't see your markup for the selected element with class="ml" thus it's almost impossible to debug why your form isn't submitting the values without seeing the bigger picture (i.e. it may be outside the form element). You could try adding the value property to the select element however jQuery should be able to pick up selected options missing the value property by using the text value instead.

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

How can I keep ng-model in sync with a select element after ng-options removes the selected option

I have a select element with an ng-model and ng-options on it. ng-options makes the possible selections dynamic however I have noticed that when ng-options updates the options ng-model is not also getting updated. For example if the select element has the value of "foo" selected then the ng-options model is updated and "foo" is no longer an option the selector updates to blank but ng-model still shows "foo" as its value. I would expect that ng-model would update as well to equal null. The only thing I can think of is to add a watch on items but that seems kind of lame. What is the best way to get ng-model to stay in sync with the select element in this scenario?
<div ng-controller="MyCtrl">
<p>Selected Item: {{foo}}</p>
<p>
<label>option</label>
<select ng-model="foo" ng-options="item.val as item.label for item in items">
<option value="">Select Something</option>
</select>
</p>
<button ng-click="remove()">Remove Second Item Option</button>
<p>{{items}}</p>
</div>
Here is the jsfiddle to illustrate the issue. http://jsfiddle.net/dberringer/m2rm8Lh6/2/
Note: I'm aware I could manually update the foo value with the delete method. This method is just to illustrate the issue.
Thanks for your feedback.
Update: I fixed a typo where referred to ng-options as ng-select.
change the button like
<button ng-click="remove(2)">Remove Second Item Option</button>
change the remove function
$scope.remove = function(removeIndex) {
if($scope.foo == removeIndex) {
$scope.foo = null;
}
$scope.items.splice(removeIndex-1,1);
};
here is the Demo Fiddle
Reason is,
ng-change is not going to trigger when,
if the model is changed programmatically and not by a change to the input value, check the Doc here
so u are not changing the select value by changing the select box instead do it using a button (programmatically) so angular will not trigger the change event on the select element and then angular doesn't know model is changed ,this might be the reason.
then what u need to do is change model value manually as $scope.foo = null;
I think angular didn't check that, once the ngOptions value changes, angular didn't do a check to see if the ngModel is exists in ngOptions.
angular.js
line 21371:
self.databound = $attrs.ngModel;
line 21828 - 21840:
return function (scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (selectCtrl && selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
You can see above code checks which option should be selected when generated the options, but i can't find a reverse check when ngOptions got updated.

Categories

Resources