Search code examples
javascripttemplatesnode-red

How to store a msg.payload into a script variable inside a ui_template node red?


I wrote this code but it doesn't work

   <script type = "text/javascript">

        var msg = {{msg.payload}}

   </script>

this method consider the {{msg.payload}} value as an error due to the '{' in the syntax, I tried different ways, but nothing works, I guess I'm missing something that I don't understand, please I m open to any suggestion.


Solution

  • The Dashboard UI node uses Angular for it's templating so you need do things a little differently.

    A good example can be found here but basically something like this:

    <script>
        //console.dir(scope) // this also works
        //console.dir(scope.msg) // This doesn't because scope.msg doesn't yet exist
    
        // Lambda function to access the Angular Scope
        ;(function(scope) {
            //console.log('--- SCOPE ---')
            //console.dir(scope) // this works but you only get it once (on startup)
            //console.dir(scope.msg) // Doesn't work for  because scope.msg doesn't yet exist
    
            //Have to use $watch so we pick up new, incoming msg's
            scope.$watch('msg.payload', function(newVal, oldVal) {
                console.log('- Scope.msg -')
                console.dir(scope.msg)
            })
    
        })(scope)
    </script>