简体   繁体   English

等效于angularjs ng-if的JavaScript

[英]JavaScript equivalent to angularjs ng-if

If I want to remove/add element on DOM I just use ng-if and the code under it does not compile into to DOM, can I do the same using pure js? 如果我想在DOM上删除/添加元素,我只是使用ng-if并且其下的代码无法编译成DOM,我可以使用纯js来做同样的事情吗? I don't want the HTML code inside my js code. 我不想在我的js代码中添加HTML代码。

Hiding it using CSS: 使用CSS隐藏它:

<div id = "infoPage" style="display: none;">

Will still insert the element to the DOM. 仍将元素插入DOM。

EDIT 编辑

The condition for showing or not is based on a flag like: 显示或不显示的条件基于如下标记:

var show = false; //or true

You can try something like this: 您可以尝试如下操作:

Idea: 理念:

  • Create an object that holds reference of currentElement and its parent ( so you know where to add ). 创建一个对象,该对象保存currentElement及其父对象的引用( 因此您知道在哪里添加 )。
  • Create a clone of current element as you want to add same element after its removed. 创建当前元素的克隆,以在删除后添加相同元素。
  • Create a property using Object.defineProperty . 使用Object.defineProperty创建一个属性。 This way you can have your own setter and you can observe changes over it. 这样,您可以拥有自己的二传手,并可以观察其变化。
  • To toggle element, check 要切换元素,请检查
    • If value is true, you have to add element. 如果value为true,则必须添加元素。 But check if same element is already available or not to avoid duplication. 但是请检查是否已有相同的元素,以避免重复。
    • If false, remove element. 如果为false,则删除元素。

 var CustomNGIf = function(element, callback, propertyName) { var _value = null; // Create copies of elements do that you can store/use it in future this.parent = element.parentNode; this.element = element; this.clone = null; // Create a property that is supposed to be watched Object.defineProperty(this, propertyName, { get: function() { return _value; }, set: function(value) { // If same value is passed, do nothing. if (_value === value) return; _value = !!value; this.handleChange(_value); } }); this.handleChange = function(value) { this.clone = this.element.cloneNode(true); if (_value) { var index = Array.from(this.parent.children).indexOf(this.element); // Check if element is already existing or not. // This can happen if some code breaks before deleting node. if (index >= 0) return; this.element = this.clone.cloneNode(true); this.parent.appendChild(this.element); } else { this.element.remove(); } // For any special handling callback && callback(); } } var div = document.getElementById('infoPage'); const propName = 'value'; var obj = new CustomNGIf(div, function() { console.log("change") }, propName); var count = 0; var interval = setInterval(function() { obj[propName] = count++ % 2; if (count >= 10) { window.clearInterval(interval); } }, 2000) 
 <div class='content'> <div id="infoPage"> test </div> </div> 


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM