Dynamically add ng-click to dynamic html from scope variable

By: Ryan Wong at

Here’s my situation:

  1. I’m binding html to a scope variable.
  2. I’m going string replace some text in this scope variable.
  3. I’m going put in some directives into this scope variable while replacing.
  4. When I display my scope variable as html, I want all the new directives inside to work as expected.

Solution:

I found this awesome directive to accomplish this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function dynamic ($c) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$c(ele.contents())(scope);
});
}
};
}

angular.module('directives', [])
.directive('dynamic', ['$compile', dynamic]);

So here’s how my controller and html will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function controller($scope){
$scope.content = 'blah blah <img src="whatever" alt="" /> blah';
var imageTag = new RegExp('<img .*alt="" />','g');
var srcTag = new RegExp('src=".*" alt','g');
$scope.imageList = $scope.content.match(imageTag);
if (!$scope.imageList){
$scope.imageList = [];
}
$scope.imageList = $scope.imageList.map(function(oneSrc){
$scope.content = $scope.content.replace(oneSrc,
oneSrc.replace('alt=""', ' alt="" ng-click="openCarousel()"'));
return oneSrc;
});

}
1
<div class="article-contents" dynamic="content"></div>

Hope this helps you out.