Javascript 我的指令下的AngularJS-html不显示

Javascript 我的指令下的AngularJS-html不显示,javascript,html,angularjs,dom,angularjs-directive,Javascript,Html,Angularjs,Dom,Angularjs Directive,在这个文件中,我有两个跨度“test1”和“test2”。显示span'test2',但我的自定义指令'test1'下的span根本没有显示或被调用到页面中。为什么? <div ng-app="HelloApp"> <div ng-controller="MyCtrl"> <search-bar/> <!-- The Search Bar Directive --> <span>test1<

在这个文件中,我有两个跨度“test1”和“test2”。显示span'test2',但我的自定义指令'test1'下的span根本没有显示或被调用到页面中。为什么?

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

测试1
测试2
角码

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
     });

    };
});
var-app=angular.module('HelloApp',[])
app.directive('searchBar',function(){
返回{
限制:“AE”,
替换:正确,
模板:“”,
链接:功能(范围、要素、属性){
元素绑定('keyup',函数(){
作用域$apply(函数(){
搜索范围(elem);
});
});
}
};
});
应用程序控制器('MyCtrl',函数($scope){
var items=[“问”、“总是”、“全部”、“好”、“一”、“富”、“黑莓”、“推特”、“强制9”、“西方人”、“运动”];
$scope.search=函数(元素){
$(“#searchbarid”).autocomplete({
资料来源:项目
});
};
});

你不能用在角度。。。这是无效的。必须使用close标记关闭指令

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

测试1
测试2
当您执行
时,这意味着您将指令元素标记视为一个自动关闭标记。自定义html元素本质上不是自动关闭的,因此您应该关闭指令中的元素,如

当前您的
test1
正在消失,因为您尚未关闭您的指令元素,所以浏览器会在其父元素关闭时自行关闭该元素,就像这里的
div
ng controller
是父元素一样

渲染前

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

测试1
渲染后

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

在指令开始对元素进行操作后,将指令元素替换为输入元素

这是


似乎适合me@timeiscoffee很好的回答。我已经添加了答案的详细版本…可能是@JamesWiseman的副本。很高兴有人喜欢它。感谢您的编辑和欣赏:)