Reputation: 3321
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.
Upvotes: 0
Views: 59
Reputation: 5242
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
Upvotes: 1