Search code examples
javascriptjqueryangularjsconflict

Jquery and AngularJs conflict


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,


Solution

  • 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.