AngularJS - 我的指令下的 html 没有显示 [英] AngularJS - html under my directive is not showing
问题描述
在这个文件中,我有两个跨度test1"和test2".跨度test2"正在显示,但我的自定义指令test1"下的跨度根本没有显示或被调用到页面中.为什么?
<div ng-controller="MyCtrl"><搜索栏/><!-- 搜索栏指令--><span>test1</span><span>test2</span>
角度代码
var app = angular.module('HelloApp', [])app.directive('searchBar', function() {返回 {限制:'AE',替换:真的,模板:'<input type="text" ng-model="searchData" placeholder="输入搜索" id="searchbarid"/>',链接:功能(范围,元素,属性){elem.bind('keyup', function() {范围.$应用(函数(){范围.搜索(元素);});});}};});app.controller('MyCtrl', function($scope) {var items = ["ask","always", "all", "alright", "one", "foo", "blackberry", "tweet","force9", "westerners", "sport"];$scope.search = 函数(元素){$("#searchbarid").自动完成({来源:物品});};});
当你在做 <search-bar/>
时,这意味着你正在考虑将指令元素标签作为一个自关闭标签.自定义 html 元素本质上不是自动关闭的,因此您应该关闭指令的元素,如
目前您的 <span>test1</span>
正在消失,因为您还没有关闭指令元素,因此浏览器会自行关闭该元素,其父元素像这里一样关闭 div
和 ng-controller
是父
渲染前
<搜索栏/><!-- 搜索栏指令--><span>test1</span>
渲染后
<搜索栏></搜索栏>
在指令之后开始处理元素 &用输入元素替换指令元素.
这里是自闭html标签列表
Within this file I have two spans 'test1' and 'test2'. The span 'test2' is showing but the span underneath my custom directive 'test1' is not showing or being called into the page at all. 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
});
};
});
As you are doing <search-bar/>
that means you are considering the directive element tag as a self-closing tag. Custom html elements are not self-closing by nature, so you should close the element of your directive like <search-bar> </search-bar>
Currently your <span>test1</span>
is disappearing because you have not closed you directive element, so the browser does close that element by itself where its parent element gets closed like here div
with ng-controller
is 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>
There after the directive start its working on the element & replace the directive element with the input element.
Here are list of self closing html tags
这篇关于AngularJS - 我的指令下的 html 没有显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!