Remove DOM-Element with AngularJS

混江龙づ霸主 提交于 2019-12-23 10:23:03

问题


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?


回答1:


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




回答2:


Try with document, not $document.

var navbar = angular.element(document.querySelector(".top-navbar")).remove();



回答3:


I feel like Ze Rubeus way of hiding the navbar makes more sense, but if you want to continue with what you have this should work:

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

Angular wraps all of it's DOM elements, so to access the element directly you need to grab the first element.



来源:https://stackoverflow.com/questions/40999224/remove-dom-element-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!