Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove DOM-Element with AngularJS

I'm trying to remove a navbar based on the current location path.

This is what I have so far:

angular.module('myModule')
  .controller('MainController', function ($location, $document) {
    if ($location.path().indexOf('resetpass') > -1) {
      var navbar = angular.element($document.querySelector(".top-navbar"));
      navbar.remove();
    }
  });

With this approach the console says:

angular.js:14110 TypeError: $document.querySelector is not a function
at new <anonymous> (main.controller.js:6)
at Object.invoke (angular.js:4762)
at $controllerInit (angular.js:10518)
at nodeLinkFn (angular.js:9416)
at compositeLinkFn (angular.js:8757)
at compositeLinkFn (angular.js:8760)
at publicLinkFn (angular.js:8637)
at angular.js:1808
at Scope.$eval (angular.js:17913)
at Scope.$apply (angular.js:18013)

What am I doing wrong?

like image 257
Codehan25 Avatar asked Dec 06 '16 15:12

Codehan25


People also ask

Which directive removes element from DOM?

remove() method removes the element from the DOM.

What is Angular element in AngularJS?

The angular. element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite.


2 Answers

use ngIf in your DOM element and do something like this:

Template :

<element ng-if="hideElemet"></element>

Controller :

if ($location.path().indexOf('resetpass') > -1) {
      $scope.hideElement = false
}

ngIf will remove the element from the DOM

like image 141
ZEE Avatar answered Dec 06 '22 19:12

ZEE


Try with document, not $document.

var navbar = angular.element(document.querySelector(".top-navbar")).remove();
like image 33
Petya Naumova Avatar answered Dec 06 '22 20:12

Petya Naumova