4

I am trying to get simple data binding to work inside a directive template in an Angular setup.

I currently have:

app.directive('myDirective', function() {
return {
    replace: true,
    restrict: 'E',  
    templateUrl: "/app/partials/template.html"
}
});

Inside my template.html, I have a simple input field, like so:

<input type="text" ng-model="name" /> 
My name is {{name}}

However, it displays '{{name}}' rather than the value typed into the input field.

If I copy this input field above outside the directive, it works.

Am I missing something when it comes to data binding within directive templates?

EDIT:

OK. One thing i missed out here as i didn't think it was relevant was this within my directive:

compile:function(){
        return function link(scope,element){
            // Call a function
            steps();
         }
    }

The reason for this was i needed to fire a Jquery function that controls elements within the template.html.

Removing this resolves the issue, but no javascript within my template works.

Is there an easy way of calling functions within a directive template on compile?

1
  • not sure exact your looking for, can you describe what u need to achieve with relevant codes? Commented Aug 31, 2015 at 11:43

2 Answers 2

1

probably you will get a error saying Error: [$compile:tplrt] Template for directive 'myDirective' must have exactly one root element. .......

you have two options to solve this.

  1. remove the replace: true from the directive definition
  2. add a root element for the template as @Andrea Ghidini's answer

here is the DEMO

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

2 Comments

Hmmm - Your example works on Plunker so there must be something else interfering with the code. I have no JS errors or Angular errors at all. The template.html was wrapped within a root element and was rendering correctly, it's just i am still seeing {{name}}.
umm can you create a plunker of your case, then it will be easy :)
0

If you see {{name}} it's because you have an error in the JS, look for the error message in the browser developer tools.

In your case the problem is the template: it must contain a single html element (link to docs), so you have to put something like:

<div>
  <input type="text" ng-model="name" /> 
  My name is {{name}}
</div>

1 Comment

That's the thing - i have no errors in the developer console and all other javascript works fine - even in the template.html. The template.html also is wrapped within a single element. To confirm, the template renders fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.