0

My problem seems relatively similar to ng-click not working in dynamically created content but the solution posted there is not working for me.

The entire goal is to have a directive that will generate some html based on a variable in the controller's scope. The generated html will have replaced all ${foobar} with a clickable span whose text is foobar that will execute a function on the controller's scope when clicked.

I have a directive:

.directive('markup', function($compile) {
    var convertParameters = function(text) {
        var matches = text.match(/\${.*}/);
        if(!matches) {
            return text;
        }
        for(var i=0;i<matches.length;++i) {
            var match = matches[i];
            var label = match.substring(2,match.length-1)
            text = text.split(match).join('<span ng-click="expose(\'' + label + '\')">' + label + '</span>');
        }
        return text;
    }
    var link = function(scope, element, attrs) {
        var text;
        if (scope.markup) {
            text = scope.markup;
        } else {
            text = element.text();
        }
        element.html("");
        element.append($compile(convertParameters(text))(scope));
    };
    return {
        restrict: 'A',
        scope: {
            markup: '=',
            expose: '&'
        },
        replace: true,
        link: link
    };
});

The directive is used in the html as:

<div class="full-text" markup="fullText" expose="exposeDoc"></div>

fullText = "This is the initial test. We have a link here: ${TestDocument}."

exposeDoc is defined on the controller's scope as:

$scope.exposeDoc = function(name) {
    $log.error(name);
};

Everything is rendered correctly but when I like on the TestDocument text nothing happens. No errors occur even the one I expect to be logged. Inspecting the element shows the ng-click attribute.

Here is a plunker showing the issue: http://plnkr.co/edit/UFjM8evq43pdm69shQWn?p=preview

Any help that can be provided would be greatly appreciated!

Community
  • 1
  • 1
Mike V.
  • 38
  • 1
  • 8

1 Answers1

0

Eureka! I figured out my issue. The problem was not with ng-click not working but the function was not provided as angular requires.

When using the directive I needed to specify the function like this:

<div class="full-text" markup="fullText" expose="exposeDoc(doc)"></div>

Where doc is just a placeholder and when calling that function from the directive I need to call it with a object where the placeholder's value is the parameter. Like this:

'<span ng-click="expose({doc:\'' + label + '\'})">' + label + '</span>'

Here is a plunker of it functioning.

http://plnkr.co/edit/1cbyXSCh5udHvc8l3qcs?p=preview

Mike V.
  • 38
  • 1
  • 8