yousef yousef - 2 months ago 12
AngularJS Question

How to add AngularJs directive dynamically from controller?

I want to add a AngularJs directive from controller.

controller code:

$scope.getLink = function(fileInfo, index)
{
if(fileInfo !== null)
{
if(fileInfo.fileType.indexOf("image") !== -1)
{
return $sce.trustAsHtml('<span ng-click="getImage('+ index +', "'
+ fileInfo.filePath +'")">view</span>');
}
else
{
return $sce.trustAsHtml('<a target="_blank" href="/phoenix/subscriber/getfile'
+ fileInfo.filePath+'">download</a>');
}
}
};
$scope.getImage = function()
{
alert("Done");
};


HTML :

<div ng-show="post.fileInfo !== null">
<div ng-bind-html="getLink(post.fileInfo,$index)"></div>
</div>


This codes work fine but the problem is that added the ng-click does not work.

Answer

There is no need to manage the view this way when angular has directives built in like ng-if or ng-show to manage this in the view

You don't need that function at all

<div ng-show="post.fileInfo !== null">
  <div>
    <span ng-if="post.fileInfo.fileType.indexOf('image') !== -1"
          ng-click="getImage($index,post.fileInfo.filePath)">view</span>
    <a ng-if="post.fileInfo.fileType.indexOf('image') === -1" 
       target="_blank" 
       ng-href="/phoenix/subscriber/getfile/{{post.fileInfo.filePath}}">download</a>

  </div>
</div>

The reason your approach was not working is when inserting directives yourself you need to use $compile

A simple directive could be used here also