Rasool Ghafari
Rasool Ghafari

Reputation: 4258

how to add `required` attribute to angularjs directive

I defined simple directive as you can see below:

(function () {
    'use strict';

    angular
        .module('myApp')
        .directive('biSelect', biSelect);

    function biSelect($compile) {
        var directive = {
            restrict: 'E',
            templateUrl: 'bi-select.html',
            scope: {
                required: '=?required'
            },
            controller: BiSelectController,
            controllerAs: 'vm'
        };

        return directive;
    }

    function BiSelectController() {
        var vm = this;
    }
})();

and this is directive template:

<select class="form-control">
    <option value=""></option>
</select>

now i want to add required attribute to select in directive when it was passed to directive, for example:

<bi-select required></bi-select>

how can i do that?

Upvotes: 0

Views: 575

Answers (1)

georgeawg
georgeawg

Reputation: 48968

In the template use the ng-required directive:

  <select ng-required="vm.required">
    <option value=""></option>
  </select>

Because the required attribute is Boolean, none of the isolate scope binding will work:

scope: {
    //WONT work
    //required: '=?required'
},

Instead inject and use the $attrs object:

function BiSelectController($attrs) {
    var vm = this;
    vm.required = !!$attrs.$attr.required;
}

The controller uses the $attrs object to detect the presence or absence of the normalized required attribute and to set vm.required to either true or false.

For more information, see

Upvotes: 1

Related Questions