1

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.

cattarantadoughan
  • 509
  • 1
  • 6
  • 15
  • I'm not quite sure I understand what you're trying to achieve. Could you perhaps provide a more complete example? – Nikolaj Dam Larsen Aug 05 '17 at 20:38
  • @NikolajDamLarsen What i want to do is instead of getting the "value" attribute from the input element, i want to get the value from the data-custom1 attribute which has a value of payment. – cattarantadoughan Aug 05 '17 at 20:43

3 Answers3

1

Two ways to do this, and you'll probably want to use the first:

<input ng-model="amount" data-custom1="{{payment}}">

<p>{{payment}}<p>

Or by using ngAttr:

<input ng-model="amount" ng-attr-payment="{{payment}}">

<p>{{payment}}<p>

The latter one is used for picky DOM APIs like the SVG DOM API. You can read more here: https://docs.angularjs.org/guide/interpolation

Sven
  • 5,155
  • 29
  • 53
1

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.

0

If you want get the input value, you have to use ng-model, only this.

And then, in your controller.js, get the input value from ng-model.

(I don't know if that's what you want to know)

ElíasMarNev
  • 124
  • 1
  • 14