In below code i am trying to add a button at compile phase, and assigned ng-click to a method from scope. During linking phase, through debugging I found the "compiledEle" contains the button, then also ng-click doesn't call the scope method.
angular.module("app", [])
.controller("ctrl1", function($scope){
$scope.myModelObj = {
name: 'Ratnesh',
value: 100
};
})
.directive("dirOne",function($compile){
return {
restrict: 'E',
scope: {
myModel : "="
},
compile: function(ele){
ele.append("<button ng-click=\"showAlert()\">click ME</button>")
return {
post: function($scope, compiledEle){
$scope.showAlert = function(){
alert("The button is clicked");
};
}
};
}
};
});
What could be the reason that the scope method doesn't get binded to button added during compile phase, but the same can be binded if I button in the template/templateUrl. Also the method get bind if in the linking phase we include a line:
$compile(compiledEle.contents())($scope);)
Also it will be get bind to the method if instead of adding "$scope.showAlert" in linking phase , we already have the method in controller !!!
.controller("ctrl1", function($scope){
$scope.myModelObj = {
name: 'Ratnesh',
value: 100
};
$scope.showAlert = function(){
alert("The button is clicked");
};
})
compile method is to do DOM manipulation and linking phase is to link compiled html to scope. So we can add new element to DOM during compile and new scope method in linking phase, so where is my expectation is getting wrong?