为什么动态添加标签(angular指令)给出undefined?

时间:2016-09-16 09:14:03

标签: javascript jquery html angularjs

我有以下代码

CONTROLLERS.JS //将cookieNotifier.html注入index.html

angular.module('app', [])
.controller('MainController', function ($scope) {

})
.directive('cookieNotification', function () {
    return {
        templateUrl: '../Pages/cookieNotifier.html'
    }
})

cookieNotifier.html

<h4 id="cookieNotifier">

    This site uses cookies.
    By continuing to browse the site, you are agreeing to our use of cookies.

    <span><button id="acceptCookies">Got It</button></span>
</h4>

INDEX.HTML //这里是angular指令

<body ng-app="app" ng-controller="MainController">

        <cookie-notification></cookie-notification>

现在在我的client.js中我想检查是否接受了cookie,如果是,请隐藏'cookie notification'栏

CLIENT.JS

$(window).ready(function() {

    var cookiesAccepted = localStorage.getItem('cookiesAccepted');

    if(cookiesAccepted === "true" || cookiesAccepted === null) {
        console.log($('#cookieNotifier').html());
        console.log("hide cookie notification bar")
    }
    else{
        console.log( "show cookie notification bar");
    }

当我想隐藏/删除h4标签时,它什么都不做。它只是给我未定义。

1 个答案:

答案 0 :(得分:2)

  

$(document).ready()中包含的代码只运行一次   页面文档对象模型(DOM)已准备好使用JavaScript代码   执行。

参考jquery ready doc

让我告诉你事件的时间表:

  • 文件为ready
  • Angular app已初始化
  • 您的指令名为

您的代码会发生什么:

if(cookiesAccepted === "true" || cookiesAccepted === null) {
    console.log($('#cookieNotifier').html());
    console.log("hide cookie notification bar")
}

甚至在初始化角度应用程序之前运行,然后调用您的指令。因此,不会有id = cookieNotifier的HTML元素,因此undefined

您可以做的是将您的显示/隐藏逻辑移动到指令本身。像这样修改你的指令。

.directive('cookieNotification', function () {
  return {
    restrict: 'E',
    replace: false,
    templateUrl: '../Pages/cookieNotifier.html',
    link: function(scope,element,attributes) {
      var cookiesAccepted = localStorage.getItem('cookiesAccepted');
      if(cookiesAccepted === "true" || cookiesAccepted === null) {
        //console.log($('#cookieNotifier').html());
        //console.log("hide cookie notification bar");
        scope.showNotification = false;
      }
      else{
        //console.log( "show cookie notification bar");
        scope.showNotification = true;
      }
    }
 }
})

然后您可以在模板中使用showNotification来显示/隐藏消息。

<h4 id="cookieNotifier" ng-if="showNotification">

This site uses cookies.
By continuing to browse the site, you are agreeing to our use of cookies.

<span><button id="acceptCookies">Got It</button></span>