-->

Add Edge Dynamically visjs

2019-07-04 14:33发布

问题:

Can anyone help me with adding edges dynamically in this visjs network? Actually, I am trying to use drag and drop to add nodes to the canvas, but I need help adding edges when I click the node and add edge dynamically to another node existing on canvas.

回答1:

You can use the vis.js 'update' function to add either nodes or edges dinamycally. You simply pass in an array with the set of either nodes or edges that you are trying to add. You call it like this:

nodes.update(updateNodesArray)

OR

edges.update(updateEdgesArray)

where nodes and edges are the vis.DataSet instances that you originally created for the network.

Full docs can be found at http://visjs.org/docs/data/dataset.html



回答2:

The intention of this answer is to help my self stop googling it, as I apparently keeps forgetting the solution, and keeps ending up here first...

It is also technically an answer to the question:

function AddEdge(from_id, to_id)
{
    network.body.data.edges.add([{from: from_id, to: to_id}])
}

It works as the network data node is a vis dataset, and updating it (also via the add/remove methods) will update the render as well.



回答3:

check this example from visjs. http://visjs.org/examples/network/other/manipulation.html

you can custom the way of adding\editing\deleting by configure your network as follow:

manipulation: {
        enabled: false,
          addNode: function (data, callback) {
              // filling in the popup DOM elements
              console.log('add', data);
          },
          editNode: function (data, callback) {
              // filling in the popup DOM elements
              console.log('edit', data);
          },
          addEdge: function (data, callback) {
              console.log('add edge', data);
              if (data.from == data.to) {
                  var r = confirm("Do you want to connect the node to itself?");
                  if (r === true) {
                      callback(data);
                  }
              }
              else {
                  callback(data);
              }
          }
      }


回答4:

var network = new vis.Network(container, datas, options)
//And then
network.addEdgeMode();

You can create edges on drag & drop



标签: vis.js