Octtavius Octtavius - 2 months ago 8
AngularJS Question

Why dynamically added tag (angular directive) gives undefined?

I have the following codes

CONTROLLERS.JS //inject cookieNotifier.html into 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 //here is the angular directive

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

<cookie-notification></cookie-notification>


And now in my client.js I want to check if cookies accepted, if so hide the 'cookie notification' bar

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


When I want to hide/remove the h4 tag, it does nothing. It simply gives me undefined.

Answer

Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Refer jquery ready doc

Let me tell you the timeline of events:

  • document is ready
  • Angular app is initialized
  • Your directive is called

What happens is your code:

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

runs even before angular app is initialized, which in turns calls your directive. so there will be no HTML element with id=cookieNotifier, hence the undefined

What you can do is move your showing/hiding logic into the directive itself. Modify your directive like this.

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

and then you can use showNotification in your template to show/hide the message.

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

Comments