2

Please see this jsfiddle: http://jsfiddle.net/viro/DK5pC/3/

What I did looks right compared to the tutorials and replies I've found, so I'm sure I'm overlooking something trivial.

I'm trying to do a directive on a html element, that will create a sibling div to display a message associated with the original element.

for example, for this html :

<input ng-model="inp" tst-msg="message" />

I would create as a sibling element:

<div class="msg">Msg:<span ng-bind="tstMsg"></span></div>

I was hoping that tstMsg in the div's scope would be bound to message in the input's scope.

Here's what the directive looks like :

angular.module('tst', [])
 .directive('tstMsg', function(){
    var template = "<div class='msg' >Msg:<span ng-bind='tstMsg'></span></div>";

    var link = function(scope,element,attrs) {
        element.parent().append(template);
        console.log("link called");
    };

    return {
        restrict: 'A',
        scope: {
          tstMsg: '='
        },
        link: link
    };
});

Well that doesn't work and I can't figure out why.

1 Answer 1

2

You need to $compile the template you're adding to the DOM. Angular hasn't had a chance to add it's handlers, for instance the ng-bind directive to that part of the dom.

So instead of just adding the element like this:

element.parent().append(template);

These steps will let Angular process your template and then add it.

newe = angular.element(template);
$compile(newe)(scope);
element.parent().append(newe);

Updated fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

question: why did you have to modify the scope object to { tstMsg: '=tstMsg' } ? I thought with just '=' it'd work.
Good catch - short answer is yes just the equal sign alone is good { tstMsg: '=' }. Background is the fiddle in your link had tstBubble: '=' which I switched to tstBubble: '=tstMsg'. Then I saw your post used tstMsg instead of tstBubble so I switched the names in the code to match your post, but using a global search and replace.
Ah, didn't notice that. I thought I had renamed it to tstMsg before posting the link.

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.