Reputation: 1025
I am having no luck figuring out why the ng-click isn't calling the function. I am compiling the angular template. I know I have an isolated scope, but the function That should be called is on the scope of the directive...
HTML:
<html ng-app="myMod">
<head>
</head>
<body ng-controller="myController">
<table>
<thead><th></th><th>Name</th></thead>
<tbody>
<tr ng-repeat="datum in data" my-element person ="datum"></tr>
</tbody>
</table>
<script src="angular.min.js"></script>
<script src="test.js"></script>
</body>
AngularJS(v1.28):
angular.module("myMod", []).
controller("myController",
function ($scope) {
$scope.data = [
{ 'name' : 'testA', 'isAdmin': true},
{ 'name' : 'testB', 'isAdmin': false},
{ 'name' : 'testC', 'isAdmin': false},
];
}).directive("myElement",function($compile){
var myTest = function(){
console.log("table cell clicked!");
};
var getTemplate = function(person){
return '<td><span ng-click="myTest()">{{person.name}}</span></td><td>test2</td>';
};
return {
restrict : 'A',
scope : {
person : "="
},
link : function (scope,element,attrs){
var template = getTemplate(scope.person);
element.html(template);
$compile(element.contents())(scope);
}
};
});
Upvotes: 0
Views: 87
Reputation: 2509
Please check out the link
http://jsfiddle.net/k66Za/103/
I have made the necessary changes and the code is working fine.
.directive("myElement",function($compile){
var getTemplate = function(person){
return '<td><span ng-click="myTest()">{{person.name}}</span></td><td>test2</td>';
};
return {
restrict : 'A',
scope : {
person : "="
},
link : function (scope,element,attrs){
var template = getTemplate(scope.person);
element.html(template);
$compile(element.contents())(scope);
scope.myTest = function(){
console.log("table cell clicked!");
};
}
};
});
Upvotes: 0
Reputation: 17064
The reason it didn't work is that you defined myTest
to be a function that is not on the scope of the directive, hence the view is not aware of that function.
Just change it to be on the scope:
return {
restrict : 'A',
scope : {
person : "="
},
link : function (scope,element,attrs){
scope.myTest = function(){
console.log("table cell clicked!");
};
var template = getTemplate();
element.html(template);
$compile(element.contents())(scope);
}
};
Upvotes: 1