AngularJS - 我指令下的html没有显示

时间:2015-06-30 20:16:53

标签: javascript html angularjs dom angularjs-directive

Please see relevant jsFiddle

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

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

    };
});

2 个答案:

答案 0 :(得分:9)

当你正在做<search-bar/>时,这意味着你正在考虑将指令元素标记作为自我结束标记。自定义html元素本质上不是自我关闭的,因此您应该关闭指令的元素,如<search-bar> </search-bar>

目前您的<span>test1</span>正在消失,因为您尚未关闭指令元素,因此浏览器会自动关闭该元素,其父元素将关闭,就像此处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>

在指令开始之后,它开始处理元素&amp;用input元素替换指令元素。

以下是list of self closing html tags

Working Fiddle

答案 1 :(得分:0)

你无法使用角度...它只是无效。您必须使用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>