The angular code placed on jsfiddle is regarding a custom directive, that uses $compile($element)($scope)
and causes the ng-click action to happen twice:
My questions are:
- I would like to understand, why is the ng-click action happening twice?
- What is the purpose of calling
$compile($element)($scope)
? - what happens if it is not called, under what circumstances should it be called?
Here are the details and what I have gathered so far:
I would like to understand, why is the ng-click action happening twice? The following line shows the custom directive "hello" and ng-click on a button. The custom directive calls $compile($element)($scope)
and that is the line that causes the action being fired twice, but I don't understand how?
Test CLICK!
Here is the code - http://jsfiddle.net/4x4L3gtw/27/
<div ng-app='myApp' ng-controller='DirectiveTestController'>
<button hello ng-click="testClick()">Test CLICK!</button>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('DirectiveTestController', ['$scope',
function ($scope) {
$scope.testClick = function () {
window.alert("hey");
console.log("hey");
}
}]);
myApp.directive('hello', function () {
return {
scope: true,
controller: ['$scope', '$element', '$compile', function ($scope, $element, $compile) {
$element.removeAttr('hello');
// $element.removeAttr('ng-click');
$compile($element)($scope);
}]
};
});
What is the purpose of calling $compile($element)($scope)
, what happens if it is not called and under what circumstances should it be called?
(click on the button and you will notice that the action happens twice)
The intent of the directive is to hide/disable based on some logic.
so in this directive I see $element.removeAttr("ng-hide")
, etc, and each time the $element.removeAttr
is called it is followed with a $compile($element)($scope)
, is the purpose to re-write the DOM?
I examined the DOM and I don't see ng-click defined multiple times. When examining the DOM (firebug), I looked at $element->0->attributes->ng-click (among other elements).
If I remove ng-click using $element.removeAttr("ng-click")
then the action only happens once.
Or if I remove the $compile($element)($scope)
the action only happens once.