Search code examples
node-red

Node Red Dashboard - Insert In List On Mqtt request


I have a mqtt node on the node-red browser ide which is listening for incoming messages about a topic.

I want to fill a list in node-red-dashboard with that information so I added a template node with that formatting:

<ul id="messagesList"></ul>

I do not only want to add this information which could be done by an angular binding I also want to delete old entries so that maximal 3 messages are in the table. So I need to run a javascript on every incoming message which can access the dashboard page.

How can I achieve that? How can I run javascript with access to the html page every time a message is coming in?


Solution

  • Add a function node, to store the messages in a flow context.

    var message = msg.payload;
    var messages = flow.get("messagesList") || [];
    
    if(messages.length < 3) {
    
      //Push to message list
      messages.push(message);
    } else {
    
      //Remove first message and add new one
      messages.splice(0,1);
      messages.push(message);
    }
    
    flow.set("messagesList", messages);
    
    msg.payload = messages;
    return msg;
    

    In the dahsboard template node, use ng-repeat to show your list, for example:

    <ul id="messagesList">
      <li ng-repeat="x in msg.payload">{{x}}</li>
    </ul>
    

    Working example:

    [{"id":"5c713e84.dacb98","type":"function","z":"47849408.20a044","name":"","func":"var message = msg.payload;\nvar messages = flow.get(\"messagesList\") || [];\n\nif(messages.length < 3) {\n\n  //Push to message list\n  messages.push(message);\n} else {\n\n  //Remove first message and add new one\n  messages.splice(0,1);\n  messages.push(message);\n}\n\nflow.set(\"messagesList\", messages);\n\nmsg.payload = messages;\nreturn msg;","outputs":1,"noerr":0,"x":310,"y":500,"wires":[["e6bdd32f.ec218"]]},{"id":"e6bdd32f.ec218","type":"ui_template","z":"47849408.20a044","group":"77d3195c.d9af28","name":"","order":0,"width":0,"height":0,"format":"<ul id=\"messagesList\">\n  <li ng-repeat=\"x in msg.payload\">{{x}}</li>\n</ul>","storeOutMessages":true,"fwdInMessages":true,"templateScope":"local","x":460,"y":500,"wires":[[]]},{"id":"87e7fba4.ccfa6","type":"inject","z":"47849408.20a044","name":"","topic":"","payload":"","payloadType":"date","repeat":"2","crontab":"","once":false,"x":150,"y":500,"wires":[["5c713e84.dacb98"]]},{"id":"77d3195c.d9af28","type":"ui_group","z":"","name":"Sensors","tab":"cd626a92.d20a78","disp":true,"width":"9"},{"id":"cd626a92.d20a78","type":"ui_tab","z":"","name":"Dashboard","icon":"dashboard"}]