Shadab Khan Shadab Khan - 5 months ago 9
HTML Question

New to AngularJS: Trying to make a directive and using it via a comment in the HTML

When I write the following code

<div ng-app="myApp">
<input type="text" ng-model="$scope.firstName"">
<input type="text" ng-model="$scope.lastName">

<p>{{ $scope.firstName + ' ' + $scope.lastName }}</p>

<!-- directive: test-directive -->

</div>

<script>
var app = angular.module("myApp",[]);

app.controller("myCtrl", function($scope) {
$scope.firstName = "Shadab";
$scope.lastName = "Khan";
});

app.directive("testDirective", function() {
return {
restrict : "M",
replace : true,
template : "Made in a directive"
};
});
</script>


The directive doesn't seem to work:
enter image description here
But when I make the following change to the template property, the directive starts working.

<div ng-app="myApp">
<input type="text" ng-model="$scope.firstName"">
<input type="text" ng-model="$scope.lastName">

<p>{{ $scope.firstName + ' ' + $scope.lastName }}</p>

<!-- directive: test-directive -->

</div>

<script>
var app = angular.module("myApp",[]);

app.controller("myCtrl", function($scope) {
$scope.firstName = "Shadab";
$scope.lastName = "Khan";
});

app.directive("testDirective", function() {
return {
restrict : "M",
replace : true,
template : "<h1>Made by a directive!</h1>"
};
});


</script>


enter image description here

I want to know why, just the addition of the h1 tags in the template property, makes the directive to start working?

Note: Ignore the input and p tags, please.

Answer

Because it's invalid

You must have a single root element in your template, it can be any element you want. for example

Invalid template

template : "Made by a directive!"

Valid template

template : "<div>Made by a directive!</div>"
template : "<a>Made by a directive!</a>"
template : "<h2>Made by a directive!</h2>"

You can see this error in the console log (open using F12)

enter image description here


https://docs.angularjs.org/error/$compile/tplrt?p0=testDirective&p1=

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,

blah blah blah

instead of simply blah blah 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.