In one of my project I had a requirement of calling a function written in angular controller from the jQuery function.
Let us understand with the help of an example:
As every controller has $scope, therefore we can access the scope of an angular element if we have an ID tag attached to the same DOM element as the ng-controller.
Following is the Html:
<body ng-app="app">
<div id="mainDiv" ng-controller="MyCtrl">
<input type="button" id="temp" value="Click Me"/>
</div>
</body>
In the angular controller following is the function which has to be called from jQuery:
angular.module('app', [])
.controller('MyCtrl', function ($scope) {
$scope.anyFunc = function () {
alert("I am called from jQuery");
};
});
Now the requirement is that we have to call anyFunc() function on the button click using jQuery.
For which we have to write the following code:
$(function(){
$("#temp").on("click",function()
{
angular.element($("#mainDiv")).scope().anyFunc();
});
});
Hope it helps..!
0 Comment(s)