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


when write 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 directive"             };         }); </script> 

the directive doesn't seem work: enter image description here when make following change template property, 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 directive!</h1>"         }; });       </script> 

enter image description here

i want know why, addition of h1 tags in template property, makes directive start working?

note: ignore input , p tags, please.

because it's invalid

you must have single root element in template, can element want. example

invalid template

template : "made directive!" 

valid template

template : "<div>made directive!</div>" template : "<a>made directive!</a>" template : "<h2>made directive!</h2>" 

you can see error in console log (open using f12)

enter image description here


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

when directive declared template (or templateurl) , replace mode on, template must have 1 root element. is, text of template property or content referenced templateurl must contained within single html element. example,

blah blah blah

instead of blah blah blah. otherwise, replacement operation result in single element (the directive) being replaced multiple elements or nodes, unsupported , not commonly needed in practice.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -