简体   繁体   中英

How to add boolean attributes to directive?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM