0

I just started look into AngularJS. While attempting to use test both Jquery and Angularjs together, an issue came up where it seemed that AngularJs somehow blocked Jquery interventino.

In the code below: I include a jquery anchor clicked event handler, which will block the anchor from directing user. However, the anchor outside of angular controller worked fine while the one inside did not run.

Is there anyway to have both Jquery and AngularJs without creating custom directive?

html:

<body data-ng-app="AngApp">
    <a href="/haha" data-disable>open</a>
    <div data-ng-controller="demoCrtl">
        <div data-ng-switch on="test")>
            <span data-ng-switch-when="1"><a href="#" data-disable>Cancel</a></span>
            <span data-ng-switch-default> its default</span>
        </div>
    </div>
</body>

javascript:

    var app = angular.module('AngApp',[]);
    app.controller('demoCrtl', ['$scope', function($scope) {
        $scope.test=1;
    }]);
    $('a[data-disable]').on('click',function(e){e.preventDefault();console.log('ha');});

I am using angularjs 1.3 and Jquery 2.1.

Many thanks,

MikeNQ
  • 653
  • 2
  • 15
  • 29
  • 2
    _"In the code below"_ - What code? Please click "edit" and add the relevant JS and html. – nnnnnn Aug 30 '14 at 07:04
  • Sorry, I'm trying to figure out how to add jsfiddle link. Pasting the code in code block give me an error when submit. – MikeNQ Aug 30 '14 at 07:10
  • Mixing angularjs and jquery is a bad idea - especially the way you are trying to do it. I recommend you read this excellent reply about switching from jquery to angular by @josh-david-miller : http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background/15012542#15012542 – chriskelly Aug 30 '14 at 09:40
  • Indeed, thank you for the link. – MikeNQ Aug 30 '14 at 14:19

2 Answers2

1

You dont need to include jQuery to your app. because it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.

Check angular.element

Narek Mamikonyan
  • 4,601
  • 2
  • 24
  • 30
1

Don't use jQuery code like this in your controller. You should be using the ngClick directive and binding it to an action in your controller.

In your view:

<a ng-click="disable()" ng-disabled="disabled">disable</a>

In your controller

$scope.disabled = false;
$scope.disable = function () {
    console.log('disable clicked');

   // maybe do something else

     $scope.disabled = true;
 } 

This does not replicate what you are trying to do, but more gives an example of how to bind actions in your controller to elements in your view with the ngClick directive as well as disable elements with the ngDisable directive.

Martin
  • 15,820
  • 4
  • 47
  • 56
  • Thanks, I realize that angularjs perceive architecture completely different from common jquery. – MikeNQ Aug 30 '14 at 14:18