I'm just starting with Angular JS and i find it very handy in terms of data handling.
My question, is it possible to bind a custom attribute by html alone? Specifically with the select element.
Instead of getting the value attribute, i want to get a custom attribute from the option tags under select element.
Just to be clear, instead of displaying the "value" of the input element, i want to display what's inside the data-custom1 which is the word "payment".
Example would be:
<select ng-model="colors">
<option data-color-hex="#2ba2ba" value="1"> Color A<option>
<option data-color-hex="#222222" value="2"> Color B<option>
<option data-color-hex="#cacaca" value="3"> Color X <option>
</select>
<p>{{display the data-color-hex value here}} </p>
If i select an option from the select element, the data-color-hex is displayed in the
element instead of value 1,2,3.
You first need to set a name
for your select
:
<select name="colors" ng-model="$ctrl.colors">
<option value="1" data-custom1="paymentA">1</option>
<option value="2" data-custom1="paymentB">2</option>
<option value="3" data-custom1="paymentC">3</option>
</select>
Then, you can create a method in your ctrl
which returns the data-custom1
attribute from the selected option:
$ctrl.getDataCustomFromSelect = function(selectName) {
return document.querySelector('select[name="' + selectName + '"] option:checked')
.getAttribute('data-custom1');
}
You can get that in your template doing:
<p ng-bind="$ctrl.getDataCustomFromSelect('colors')"><p>
Fiddle with that solution: https://jsfiddle.net/virgilioafonsojr/b002ccja/
I hope I understood your problem correctly and it solves the issue.