Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  64] [ 2]  / answers: 1 / hits: 21034  / 9 Years ago, sun, march 29, 2015, 12:00:00

How to call angularjs function or controller from jquery
I am new to this angularjs
here is my function here i have to pass the var1 and var2 from jquery i have searched many articles but i cant understand. Please help me



<script type=text/javascript>

function customersController($scope, $http) {
$http.get(https://tic.com/testingservice/HttpService.svc/operator/var1/var2)
.success(function (response) { $scope.names = response; });
}



More From » jquery

 Answers
5

If I speak general, there can be cases when jQuery use is need in Angularjs app i.e. jQuery plugin is used that isn't available in Angular version.



Every Controller has $scope/this and You can access the scope of an angular element if you have an ID tag attached to the same DOM element as the ng-controller:



the DOM:



<div id=myctrl ng-controller=MyCtrl></div>


your controller:



function MyCtrl($scope) {
$scope.anyFunc = function(var1, var2) {
// var1, var2 passed from jquery call will be available here
//do some stuff here
}
}


in jQuery you do this and it will access that controller and call that function :



angular.element('#myctrl').scope().anyFunc('value1','value2');


Running Sample





angular.module('app', [])
.controller('MyCtrl', function ($scope) {
$scope.anyFunc = function (var1, var2) {
alert(I am var1 = + var1);
alert(I am var2 = + var2);
};
});

$(function(){

$(#hit).on(click,function(){

angular.element($(#myctrl)).scope().anyFunc('VAR1 VALUE', 'VAR2 VALUE');

});

});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js></script>

<div id=myctrl ng-app='app' ng-controller=MyCtrl>
Call via jQuery
<button id=hit>Call</button>
</div>





Happy Helping!


[#67265] Friday, March 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierceabnerc

Total Points: 430
Total Questions: 92
Total Answers: 102

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;