【问题标题】:AngularJS - html under my directive is not showingAngularJS - 我的指令下的 html 没有显示
【发布时间】:2015-09-17 19:22:50
【问题描述】:

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>

角度代码

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

    };
});

【问题讨论】:

标签: javascript html angularjs dom angularjs-directive


【解决方案1】:

正如您所做的&lt;search-bar/&gt;,这意味着您正在将指令元素标签视为自闭合标签。自定义 html 元素本质上不会自动关闭,因此您应该关闭指令的元素,例如 &lt;search-bar&gt; &lt;/search-bar&gt;

目前您的&lt;span&gt;test1&lt;/span&gt; 正在消失,因为您尚未关闭指令元素,因此浏览器会自行关闭该元素,其父元素会像这里一样关闭divng-controller 是父元素

渲染前

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

渲染后

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

在指令开始处理元素并用输入元素替换指令元素之后。

这里是list of self closing html tags

Working Fiddle

【讨论】:

  • @JamesWiseman 很高兴有人喜欢它。感谢您的编辑和赞赏:)
【解决方案2】:

您不能在角度中使用...它只是无效。您必须关闭指令,带有关闭标签

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多