AngularJS - 我的指令下的html没有显示 [英] AngularJS - html under my directive is not showing

查看:453
本文介绍了AngularJS - 我的指令下的html没有显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅相关的jsFiddle

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

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>

角色代码

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

    };
});


推荐答案

正如你所说 ; search-bar /> 表示您正在将指令元素标记视为自动关闭标记。自定义html元素不是自我关闭的,所以你应该关闭你的指令的元素,如< search-bar> < / search-bar>

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>

目前您的< span> test1< / span> 正在消失,因为您尚未关闭指令元素,因此浏览器会自动关闭该元素,其父元素会像这样 div ng-controller 是父级

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

呈现之前

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

渲染后

<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.

这里是 自我关闭html标签列表

工作小提琴

这篇关于AngularJS - 我的指令下的html没有显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆