0

I want to replace sometext by defined text with the help of angular JS. My html is

<!DOCTYPE html>
<html>
<head>
    <title>Directive</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body ng-app="myApp">
    <div hello-world>sometext</div>
</body>
</html>

and JS is

var app = angular.module('myApp', []);

app.directive('helloWorld', function() {
  return {
      restrict: 'AE',
      replace: 'true',
      template: '<input type="text" ng-model="headline"/><br/>{{headline}}'
  };
});

My browser says that,

Error: [$compile:tplrt] Template for directive 'helloWorld' must have exactly one root element....

How to solve this. Thank you.

1
  • 1
    Try to wrap the template inside a div Commented Apr 11, 2015 at 16:15

1 Answer 1

1
return {
      restrict: 'AE',
      replace: 'true',
      template: '<div><input type="text" ng-model="headline"/><br/>{{headline}}</div>'
  };

should do it. The important part is the div tag wrapping the template string.

As Sajeetharan rightly commented, there must be only one wrapper for the template that will replace your directive.

Otherwise, the replacement operation would result in a single element (the directive) being replaced with multiple elements or nodes, which is unsupported and not commonly needed in practice.

It does not have to be a div, though; so when you have 'replace':true, your template must be like:

<any-tag-you-wish>template content</any-tag-you-wish>

Please read doc for template in directive with replace mode on

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

4 Comments

What Changes I have to make if I declare my directive as comment i.e. <!-- directive:hello-world -->
well the change is in the template property of your directive: 'template':'<div><input type="text" ng-model="headline"/><br/>{{headline}}</div>'; will edit the answer...
Oh sorry, you need this: restrict: 'M'
Yes. restrict: 'M'. Thanks for helping.

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.