0

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?

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.