1

I am new to Angularjs and are trying to create a dictionary directive that searches and replaces texts with anchor tags. The search and replace part works fine but i can't get the ng-click to work.

HTML

<div mk-dct>Lorem ipsum [dolor] sit [amet]</div>

Angular

app.directive('mkDct', function () {
var pattern = /\[([^\]]+)\]/g;
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var txt = element.html();
        var m = txt.match(pattern);

        for(var i = 0; i < m.length; i++){
            var word = m[i].substring(1, m[i].length-1);
            txt = txt.replace(m[i], '<a class="dict-item" ng-click="func(\''+word+'\')" href="#">'+ word + '</a>');
        }

        element.html(txt);
    }
};

UPDATE
The commented lines below made it work as expected.

app.directive('mkDct', function ($compile) {
var pattern = /\[([^\]]+)\]/g;
return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attrs) {
        var txt = element.html();
        var m = txt.match(pattern);

        for(var i = 0; i < m.length; i++){
            var word = m[i].substring(1, m[i].length-1);
            txt = txt.replace(m[i], '<a class="dict-item" ng-click="func(\''+word+'\')" href="#">'+ word + '</a>');
        }

        // Compile to template.
        txt = $compile(txt)(scope);

        // Clear and append.
        element.empty().append(txt);
    }
};

});

1 Answer 1

1

You need to compile your element.

EDIT Add compile statement after loop as discussed in comments below.

txt = $compile(txt)(scope);
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately this creates an error "txt.replace is not a function". Btw: I included $compile in the directives main function declaration to get $compile to work.
@Andbil, use compile after loop
I included the compile after the loop like this: txt = $compile(txt); This seems to output the code of the link function starting i with "function publicLinkFn..."
@Andbil, yep, you need link compiled element with scope, so it should be like $compile(txt)(scope)
Great! In conjunction with append() and empty() instead of just html() it worked. Thanks guys and will update the code with the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.