Tarun Dugar Tarun Dugar - 5 months ago 37
AngularJS Question

Dynamic ng-click not working

I have a directive that dynamically creates an element with

ngClick
handler and appends it to the directive element:

app.directive('truncate', ['$compile', function($compile) {
return {
restrict: 'A',
scope: {
textStr: '=',
truncLength: '='
},
link: function(scope, element, attrs) {
scope.open = false;

scope.more = function() {
console.log('hello');
}

scope.less = function() {
var outputEle = angular.element('<span>' + scope.textStr.substring(0, scope.truncLength) + '<a data-ng-click="more()"> more...</a>' + '</span>');
$compile(outputEle, scope);
element.append(outputEle);
}
scope.less();
}
}
}]);


The dynamic element is being added but dynamic
ngClick
(defined inside the less function) is not working. What am I doing wrong?

Answer

The compilation part is wrong. It should be

var outputEle = angular.element('<span>' + scope.textStr.substring(0, scope.truncLength) + '<a data-ng-click="more()"> more...</a>' + '</span>');
$compile(outputEle)(scope);
element.append(outputEle);

Note that $compile(outputEle) returns linking function, which you use next to connect DOM element to the scope.

Comments