Reputation: 5052
I wanted to make a common component which can be re-used and hence created a directive, but the issue is I am not able to figure out a way to trigger & capture the click event of an element inside the template used inside the directive.
Following is the code snippet that may help in understanding the issue:
myApp.directive('importPopup', function ($timeout) {
return {
restrict: 'E',
template: '<button class="btn btn-primary save-btn floatLeft">Import
</button>',
scope: {},
link: function(scope, element, attrs) {
element.bind('click', function(){
angular.element('body').append('
<div class="popupContainer">
<button> x </button>
<div>
Enter Number: <input type="text" ng-model="noToImport">
</div>
<button type="button" id="importBtn" ng-click="importClick()">Import</button>
</div>');
});
scope.importClick = function() {
console.log(' import document for Rule no - ' + scope.noToImport);
}
}
}
});
I am unable to
1) trigger the event on click of #importBtn
2) and also unable to fetch the value for model - 'noToImport'
Here is the Link to the Plunkr
Any help will be appreciated. Thanks in advance.
Upvotes: 1
Views: 1077
Reputation: 305
Try this:
var app = angular.module('MainApp',[]);
app.directive('importPopup',function ($compile) {
return{
restrict: 'E',
template: '<button class="btn btn-primary save-btn floatLeft">Import </button>',
link: function(scope, element, attrs) {
element.bind('click', function(){
angular.element(document).find('body').append($compile('<div class="popupContainer"><button> x </button><div>Enter Number: <input type="text" ng-model="noToImport"></div><button type="button" id="importBtn" ng-click="importClick()">Import</button></div>')
(scope))
});
scope.importClick = function() {
console.log(' import document for Rule no - ' + scope.noToImport);
}
}
}
});
I've forked your code here: Plunker
When adding templates to an angular app you must first "compile" it. This means you create a linking function from your template and then link the template to the angular app, by that you "tech" angular that this code is part of the app and that it needs to consider it in a digest cycle. You can read more about $compile here: $compile
Upvotes: 3