1

I am new to AngularJS, please help me to solve this problem. How can I call the jQuery function from AngularJS.

HTML:

<div ng-controller="TestClickController">
<button ng-click="clickFunc()">Test click</button></div>

Script:

<script>
var app = angular.module('myApp', []);
app.controller('TestClickController', function($scope) {
    $scope.clickFunc = function() {
        $('#div1').html('User clicked');
    };
});
</script>

When the button is clicked, I get the error "Error: $ is not defined".

Tushar
  • 85,780
  • 21
  • 159
  • 179
Jack
  • 329
  • 2
  • 7

4 Answers4

9

Your error would mean that jQuery isn't included/not yet loaded.

I would recommend though if you use Angular, then use the Angular way to solve this stuff:

<div ng-controller="TestClickController">
    <button ng-click="clickFunc()">Test click</button>

    <div>
        <!-- This text will be updated when the button is clicked -->
        {{ testText }}
    </div>
</div>

Controller:

app.controller('TestClickController', function($scope) {
    $scope.testText = '';
    $scope.clickFunc = function() {
        $scope.testText = 'User clicked';
    };
});

JSFIDDLE

One of the unwritten rules of angular is: "If you need to use jQuery to do stuff, then you probably do something wrong."

devqon
  • 13,818
  • 2
  • 30
  • 45
0

Error: $ is not defined

Normally means Jquery has not been included properly....

BigGrecian
  • 43
  • 5
0

This is because you have not have included jquery. Otherwise this should have worked.

Also when you include jquery, you should do it before you include angular so that angular takes full advantage of presence of jquery. And you can then use angular.element instead of $.

angular.element('#div1').html('User clicked');

One more thing, when you are using jquery functions, it is advisable to do them in a service or a directive. Controller is not meant to call other libraries functions. This is just a convention which helps in better testable code.

Kop4lyf
  • 4,520
  • 1
  • 25
  • 31
0

I did not see an ng-app, which could have been your issue. Or you have not included jQuery before Angular is bootstrapped.

<div ng-app="myApp">
    <div ng-controller="TestClickController">
       <button ng-click="clickFunc()">Test click</button>
    </div>
    <div id="div1"></div>
</div>

The JavaScript:

var app = angular.module('myApp', []);
   app.controller('TestClickController', ['$scope', function($scope) {
   $scope.clickFunc = function() {
       console.log();
       $('#div1').html('User clicked');
   };
}]);

Here is a working js fiddle:

http://jsfiddle.net/bwz9e0Ly/

Michael Wilson
  • 1,548
  • 3
  • 21
  • 44