AngularJS - html not showing in my directive

Refer to the appropriate jsFiddle

Inside this file, I have two tests, test1 and test2. The space 'test2' is shown, but the range under my custom directive 'test1' does not appear at all or is not called to the page. Why?

<div ng-app="HelloApp"> <div ng-controller="MyCtrl"> <search-bar/> <!-- The Search Bar Directive --> <span>test1</span> </div> <span>test2</span> </div> 

Angular Code

 var app = angular.module('HelloApp', []) app.directive('searchBar', function() { return { restrict: 'AE', replace: true, template: '<input type="text" ng-model="searchData" placeholder="Enter a search" id="searchbarid" />', link: function(scope, elem, attrs) { elem.bind('keyup', function() { scope.$apply(function() { scope.search(elem); }); }); } }; }); app.controller('MyCtrl', function($scope) { var items = ["ask","always", "all", "alright", "one", "foo", "blackberry", "tweet","force9", "westerners", "sport"]; $scope.search = function(element) { $("#searchbarid").autocomplete({ source: items }); }; }); 
+6
source share
2 answers

As you do <search-bar/> , this means that you consider the directive element tag as a self-closing tag. Custom html elements are not self-closing in nature, so you should close your directive element, for example <search-bar> </search-bar>

Currently, your <span>test1</span> disappearing because you did not close your directory element, so the browser closes this element itself, where its parent element is closed, as here the div with ng-controller is the parent

Before rendering

 <div ng-controller="MyCtrl"> <search-bar/> <!-- The Search Bar Directive --> <span>test1</span> </div> 

After rendering

 <div ng-controller="MyCtrl"> <search-bar></search-bar> </div> 

After the directive begins its work on the element and replaces the directive element with the input element.

Here is a list of self-closing html tags

Working script

+9
source

you cannot use in angular ... its just not valid. You must close the directive with the tag tag

 <div ng-app="HelloApp"> <div ng-controller="MyCtrl"> <search-bar> </search-bar><!-- The Search Bar Directive --> <span>test1</span> </div> <span>test2</span> </div> 
0
source

Source: https://habr.com/ru/post/990053/


All Articles