AngularJS, the Digest Loop, Directives and jQuery
I've been struggling with understanding when and how to use jQuery inside an AngularJS directive and have the data binding work as expected. I've got a good example I put together that shows how to do this as well as shows when you need to use the scope.$apply().
by pkellner99
HTML
<body ng-app="myapp">
<h1>AngularJS, the Digest Loop, Directives and jQuery</h1>
<h2><a href='http://peterkellner.net/2014/10/30/angularjs-the-…ves-and-jquery/' target='_blank'>Blog Post</a></h2>
<h3><a href='http://peterkellner.net/'>PeterKellner.net</a></h3>
<div ng-controller="TopController">
<table border="1" cellpadding="10">
<tr>
<td>cnt Angular</td>
<td>{{cntAngular}}</td>
</tr>
<tr>
<td>cnt jQuery</td>
<td>{{cntjQuery}}
</tr>
</table>
<input type="checkbox" ng-model="ApplyChecked">Execute scope.$apply() in directive after increment
<br>
<a ng-click='incrementCntAngular()' href=''>Increment Cnt Angular</a>
<hr/>
<button incrementj-query-directive>
incrementjQueryDirective
</button>
<hr/>
</div>
<script>
</script>
</body>
</html>
JavaScript
var myApp = angular.module('myapp', []);
myApp.controller('TopController', function($scope) {
$scope.cntAngular = 0;
$scope.cntjQuery = 0;
$scope.incrementCntAngular = function() {
$scope.cntAngular++;
}
}).directive('incrementjQueryDirective', function() {
return {
template: '<br/><p>cntAngular: {{cntAngular}} cntjQuery: {{cntjQuery}}</p><br/>',
link: function(scope, element) {
element.bind('click', function() {
scope.cntjQuery++;
if (scope.ApplyChecked == 1) {
// WITHOUT THIS LINE THE DIGEST LOOP IS NOT RUN ON INCR
scope.$apply();
}
})
}
}
});