I have code similar to the below code to trigger a click
event in an Angular app. Why is not the event triggering?
var app = angular.module("myApp", [])
app.directive('myTop',function($pile) {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function (scope, element) {
var childElement = '<button ng-click="clickFunc()">CLICK</button>';
element.append(childElement);
$pile(childElement)(scope);
scope.clickFunc = function () {
alert('Hello, world!');
};
}
}
})
I have code similar to the below code to trigger a click
event in an Angular app. Why is not the event triggering?
var app = angular.module("myApp", [])
app.directive('myTop',function($pile) {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function (scope, element) {
var childElement = '<button ng-click="clickFunc()">CLICK</button>';
element.append(childElement);
$pile(childElement)(scope);
scope.clickFunc = function () {
alert('Hello, world!');
};
}
}
})
Share
Improve this question
edited Dec 10, 2015 at 9:26
Shashank Agrawal
25.8k11 gold badges96 silver badges125 bronze badges
asked Dec 10, 2015 at 2:28
freddy83freddy83
631 silver badge5 bronze badges
1 Answer
Reset to default 7Change your pile statement like this:
$pile(element.contents())(scope);
You were passing a DOM string childElement
which is really not a DOM element instead it is a string. But the $pile
needs the DOM element(s) to actually pile the content.
var app = angular.module("myapp", []);
app.directive('myTop', ['$pile',
function($pile) {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function(scope, element) {
var childElement = '<button ng-click="clickFunc()">CLICK</button>';
element.append(childElement);
$pile(element.contents())(scope);
scope.clickFunc = function() {
alert('Hello, world!');
};
}
}
}
])
<html>
<body ng-app="myapp">
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<my-top></my-top>
</body>
</html>