A.kurt
A.kurt

Reputation: 71

AngularJS: How to dynamically add a function to a appended html element within a directive

I have created a directive for handling all links across my web app. I have successfully generated different link objects depending on what role the logged in user have. The following code works, except when I try to add functionality to ng-click within "htmlElement".

      $scope.test = test;
      function test() {
                console.log("test")
            }

       var htmlElement = "<li ng-click=\"test()"\"><a href=\"" +
                link.href + "\" target=\"" +
                link.target + "\">" +
                link.title + "</a></li>";
       element.append(htmlElement);
...
       $compile(element)($scope);
       element.append(element);

When hitting the generated element, ng-click and test() does not fire. What am I doing wrong?

Upvotes: 0

Views: 65

Answers (2)

Tom el Safadi
Tom el Safadi

Reputation: 6776

As I understood you are trying to display a button whether the user has the required role to see or use the button. This is not a good way with what you are trying to do.

The approach is the following: Add a scope where the role for the user is stored, then inside the controller evaluate it (if the user can see the button). Then use ng-show inside the html to hide/view the button.

Example: (inside of html)

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="userRole"></div>

Instead of the div use your button or whatever you want to...

(inside of your controller or script)

<script>
if (user.Role == "Admin")
{ 
   // this will show the button on the view
   $scope.userRole = true 
}
else
{
   // this will hide the button from the view
   $scope.userRole = false;
}
</script>

Upvotes: 0

Andrei CACIO
Andrei CACIO

Reputation: 2119

Try putting the test() function on the directive's scope, like so:

       $scope.test = function() {
                console.log("test")
            }

       var htmlElement = "<li ng-click=\"test()"\"><a href=\"" +
                link.href + "\" target=\"" +
                link.target + "\">" +
                link.title + "</a></li>";
       element.append(htmlElement);

...

   $compile(element)($scope);
   element.append(element);

test() is a private function within the directive's link function. It isn't accessible by the ng-click because it is not on the $scope.

Hope this helps.

Upvotes: 1

Related Questions