Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree)

Here is an example of what I currently have:

<item><input value"item A #1"><button>insert under</button></item>
<item><input value"item B #2"><button>insert under</button></item>
<item><input value"item C #3"><button>insert under</button></item>
<item><input value"item D #4"><button>insert under</button></item>

When clicking on "insert under" for Item C, I want to insert a new item between Item B and Item C, focusing the input of this new item.

Any ideas on how to achieve this functionality?

Thank you very much!

Answer №1

It would have been easier if you had provided a specific sample of your data and html, but I have given a generic solution that should still be helpful.

1) Creating an "add below" button

The ui-tree simply renders your tree model. In Angular, all you need to do is manipulate the data to add a node under another one. To achieve this, you need to access an array of sibling nodes and the current index. The index can be accessed using $index as ui-tree uses the standard ngRepeat. Getting the array of siblings is a bit trickier. By looking at the documentation, you can find that $parentNodesScope refers to the scope of the tree-nodes (siblings container), which contains $modelValue representing the siblings array. Here is how you can accomplish it:

<button ng-click='$parentNodesScope.$modelValue.splice($index+1,0,{value:"New",nodes:[]})'>Add below</button>

Replace {value:"New",nodes:[]} with the structure of the data you are working with.

2) Setting focus on the input of the added node

There are various ways to focus inputs in Angular, such as the method discussed in this Stack Overflow answer. Personally, I find this solution most effective. It focuses on elements as they are inserted into the DOM, including when ui-tree re-renders the tree with new nodes. One drawback is that after the initial page load, the focus will default to the last node added, which you can handle accordingly.

You can view a demo of the implementation here: Demo Link

Answer №2

Give this a try. I've implemented onclick event listeners on the HTML buttons:

<item><input value="item A #1"><button onclick="onClickItem(this);">insert under</button></item>
<item><input value="item B #2"><button onclick="onClickItem(this);">insert under</button></item>
<item><input value="item C #3"><button onclick="onClickItem(this);">insert under</button></item>
<item><input value="item D #4"><button onclick="onClickItem(this);">insert under</button></item>

Next, take a look at the JavaScript code:

<script>
function onClickItem( clickedItem)
{
    var newElement = document.createElement( "item");
    newElement.innerHTML = '<input><button>insert under</button>';

    if( newElement.addEventListener)
        newElement.lastChild.addEventListener( "click", function() { onClickItem( newElement) });
    else if( newElement.attachEvent)
        newElement.lastChild.attachEvent( "onclick", function() { onClickItem( newElement) });  // for IE8 or earlier

    var parentNode = clickedItem.parentNode.parentNode;
    newElement = parentNode.insertBefore( newElement, clickedItem.parentNode.nextElementSibling );
}
</script>

The initial lines of the JavaScript create the new item based on the original items. It also adds an event listener to ensure the new item behaves similarly to the existing ones.

Finally, it uses the insertBefore method in the DOM to place the new item after the clicked element. This setup allows for cascading creation of additional items by clicking on each inserted button. Hopefully, this meets your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to automate the process of constructing a dependency in the package.json file?

Currently, I am using firebaseui and require building it with French localization because the localized versions are not available on npm. In my current package.json file, the dependencies section looks like this: "dependencies": { "firebaseui": "^3.5 ...

Displaying a collection of items using ReactJS

Hey there! I have an array of objects containing comments for a particular item, and I only want to display the first 10 on the page. Below that list, I'm looking to add a button that allows users to see the next set of 10 comments when clicked. It&a ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Creating a mouseover popup window for a specific text citation based on its ID using JavaScript in XSLT

I have implemented the following XML code for citations related to figures, tables, and reference citations. When hovering over the citation, it should display the relevant text based on the id and href. XML code for Citation: Fig. <link href="#ecog34 ...

An issue with the image filter function in JavaScript

I am currently working on a simple application that applies image filters to images. Below is the code I have written for this purpose. class ImageUtil { static getCanvas(width, height) { var canvas = document.querySelector("canvas"); canvas.widt ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

"PHP error: Accessing an undefined offset index 2

I'm currently working on a code snippet where I need to iterate through an array and replace specific characters within the 'color_codes' values. While the code is functioning correctly, I'm encountering an error message stating undefin ...

What is the method for implementing a dropdown box with select and non-select checkboxes, similar to the example shown in the image, using AngularJS?

https://i.sstatic.net/CTx8K.jpg I am seeking assistance in incorporating the image below into a dropdown menu using angularjs ...

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

What is the best way to convert an ajax get request into a post request using jQuery?

I'm interested in transforming a GET request to a POST request: $.ajax({ url: '/items?ids=' + value.join(','), method: 'get', dataType: 'json' }) What changes do I need to make to turn this into a ...

Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration: globalSetup: path.resolve(srcPath, 'TestUtils', 'global ...

I am having difficulty with my JavaScript code not being able to interpret the JSON output from my PHP code. Can anyone help me troubleshoot

Having trouble working with an AJAX call and handling the JSON object it generates in JavaScript? Here's a sample snippet of PHP code returning the JSON object: echo json_encode(array("results" => array(array("user" => $member['user'] ...

how can you activate a modal without relying on bootstrap?

Could anyone suggest a more efficient way to create a pop-up modal triggered by a button click without relying on bootstrap? I've attempted different methods but haven't achieved the desired result. Here's a sample plunker for reference. Any ...

Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works: When the index.html pa ...

What is the best way to replicate touch functionality on mobile browsers for both Android and iPhone devices?

Recently, while developing a web application, I ran into an issue on mobile browsers where the :active pseudo class wasn't functioning properly. I am currently utilizing CSS sprites and looking for guidance on how to simulate clicks for mobile browser ...

Delete the hidden attribute from an HTML element using a JavaScript function

Hey there! I have a question for you. Can you assist me in removing an attribute (Hidden) using an Input type button? Here is the script: Thank you for your help! <input type="button" onclick="myfunction()" value="Test"> <hr> <button id= ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Conceal the current component prior to displaying the component associated with Navlink in React Router

Currently, I am in the process of developing a single-page web application using React routing. My goal is to hide the current component before rendering the next component when a NavLink is clicked, similar to how <a href="someLink"> works in HTML. ...