1

I am trying to wrap Bootstrap 3's modal in a Angular directive. I get into the link function, but I am not able to call the Bootstrap .modal() function. Here is my html:

<h1>This is a test!!!</h1>
<button ng-click="test()">This is a button</button>

<div id="myModal" class="modal fade" bsmodal>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

And here is my directive:

App.directive('bsmodal', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.modal('show');
    }
  };
});

When I get to the element.modal('show'), I get the error,TypeError: Object #<Object> has no method 'modal'. The element object looks like a jQuery wrapped object, but it still does not have the method. The part I don't understand is I can call $('myModal').modal() in the link function and everything works like it is supposed to work.

So my questions are

  1. What is the difference between an element and a jQuery wrapped object? (They look the same)
  2. How do I call the modal() function on the element inside the link function?

1 Answer 1

1

Angular uses a reduced version of jQuery, jqLite which supports a subset of the functions offered by jQuery.

It looks like you are loading jQuery anyway in your page. If you load it before angular, angular will use it instead of using jqLite and you should be able to call element.modal('show').

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

2 Comments

I understand it offers a subset of the functions offered by jQuery, so I guess that means that it doesn't have the same plugin structure as jQuery?
@jhamm Plugins which attach themselves to jQuery object will not be accessible if you are using jqLite, yes. However, if jquery is loaded before angular, there should be no difference between $('myModal') and element. Try it and see if that works.

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.