简体   繁体   中英

how to create an angular directive to load jquery?

i want to use jSignature jquery plugin with my mvc+angular js project,but i am unable to load the jquery in the project since i dont have a proper directive to load it,help is needed.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script>
<script src="jquery.signature.js"></script>
<script>
    $(function () {
        $('#sig').signature();
        $('#clear').click(function () {
            $('#sig').signature('clear');
        });
        $('#json').click(function () {
            alert($('#sig').signature('toJSON'));
        });
        $('#svg').click(function () {
            alert($('#sig').signature('toSVG'));
        });
    });
</script>
</head>
<body>

this is the code i used alongside the jquery plugin,but a directive is required to properly load the jquery,some help is needed to write the directive?

You don't need a directive to load jQuery. Just include jQuery before including AngularJS, angular will use jQuery instead of jQlite.

The best practice to include third party js code is to create a directive that wraps code in the link function:

app.directive('myDir', function() {
  return {
    link:link
  };

  function link($scope, $element, $attr){

      (function ($) {
        $('#sig').signature();
        $('#clear').click(function () {
            $('#sig').signature('clear');
        });
        $('#json').click(function () {
            alert($('#sig').signature('toJSON'));
        });
        $('#svg').click(function () {
            alert($('#sig').signature('toSVG'));
        });
      }(jQuery));
  });

});

And finally include the directive where needed.

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