Sumanth madey
Sumanth madey

Reputation: 788

Unable to use custom directive when ng-model is used

While trying to use custom directive with an output linked to text field im getting below issue

[$compile:tplrt] Template for directive 'myDir' must have exactly one root element. http://errors.angularjs.org/1.5.0/$compile/tplrt?p0=myDir&p1= can some one show some light here

Code

<!DOCTYPE html>
<html ng-app="myapp1">

<head>
    <title> ANGULAR</title>
    <script src="angular.min.js"></script>
    <script type="text/javascript">
        angular.module('myapp1', []).directive('myDir', function() {
            return {
                restrict: 'E',
                replace: true,
                template: '<input type="text" ng-model="title"> {{title}}'
            };
        });
    </script>
</head>

<body>
    <div>
        <my-dir>sadas</my-dir>
    </div>
</body>

</html>

Upvotes: 0

Views: 63

Answers (3)

Chandra Kudumula
Chandra Kudumula

Reputation: 334

When a directive is declared with template (or templateUrl) and replace mode on, the template must have exactly one root element. That is, the text of the template property or the content referenced by the templateUrl must be contained within a single html element.

For example,

<p>blah <em>blah</em> blah</p> instead of simply blah <em>blah</em> blah

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.

https://docs.angularjs.org/error/$compile/tplrt

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You have set your directive replace:true which is deprecated by the way. Since you are replacing element your template should compile to a single root.

If you remove replace attribute, you can use the template you have now. Demo.

   directive('myDir', function() {
        return {
            restrict: 'E', 
            // don't use deprecated option replace: true
            template: '<input type="text" ng-model="title"> {{title}}'
        };
    });

Upvotes: 1

Łukasz Staniszewski
Łukasz Staniszewski

Reputation: 668

Error message is clear I guess your template should look like this:

<div><input type="text" ng-model="title"> {{title}}</div>

instead of just:

<input type="text" ng-model="title"> {{title}}

Upvotes: 1

Related Questions