How to add attribute to node's data field in cytoscape.js?

2k Views Asked by At

I am trying to dynamically update nodes of my cy object with the "parent" field. When the elements are first loaded in from a json file, they do not have a parent field. The documentation says I should be able to set a particular data field simply with cy.data( name, value ). However, this appears to only work the attribute name is one that already exists.

I have thought to create a copy of each node to add my parent attribute to, and then remove the old node; however my graph is quite large and this seems like a last resort.

1

There are 1 best solutions below

3
Stephan T. On

I tried this with my code and got it to work properly with .move():

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  style: [{
      selector: 'node',
      style: {
        'label': 'data(id)'
      }
    },
    {
      selector: 'edge',
      style: {
        'curve-style': 'bezier',
        'target-arrow-shape': 'triangle'
      }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'a',
          parent: ''
        }
      },
      {
        data: {
          id: 'b',
          parent: ''
        }
      },
      {
        data: {
          id: 'c',
          parent: ''
        }
      },
      {
        data: {
          id: 'd',
          parent: 'p'
        }
      },
      {
        data: {
          id: 'p',
          parent: ''
        }
      }
    ],
    edges: [

    ]
  }
});

cy.bind('click', 'node', function(evt) {
  evt.target.move({
    parent: cy.getElementById('p').id()
  })
});
body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px;
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}
<head>
  <title>cytoscape-add-attribute demo</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
</head>

<body>
  <h1>cytoscape add-attribute-demo</h1>
  <div id="cy"></div>
</body>

The documentation has two versions of .data(), one for the core cy element, and one for any element, so also nodes, edges, the canvas...

I think your problem came from that, if not, let me know what code you use exactly :D THX