Peter The Angular Dude
Peter The Angular Dude

Reputation: 1188

How to fire a function from within a JSON object

I have a function that's created from one program and then in the UI of another program, I have. That first program builds the code and the second one renders it.

Here's the question.

The JSON object contains a FUNCTION as a string because that's how it's coming from the NODE SERVICE into the Angular 5.x UI

Here's the JSON

{
  "test": {
  "trigger": "load",
  "functionName": [
           "function(){if(1 === 1){console.log('hello');} else {console.log('goodbye');}" **<== CORRECTED the original single = that Johnathan caught.**
    ]
  }
}

That's the simplest way I can show it. Yes, there are "" around the {} which is INVALID JSON but the state machine we're using on the backend renders (sanitizes) it that way and on the client.

Bottom line: what I'm trying to achieve is the ability to call standard JavaScript functions like, onBLur, onChange, onHover, onMouseOver, etc...some functions are irrelevant...but we definitely need, onBlur and onChange.

I did this back in Angular 1.6 with app.js and the router whereby I called functions inside a JSON object that called the function on the controller. Wala! It was easy with $scope.$parent.functionName(arg1 if any){}

I simply wrote:

....,
onEntry: (function() {
     do something cool here...
}),
....

So, with TypeScript, how can I achieve the same thing?

I hope I'm clear with my question?

Thanks

UPDATE!!!!

Here's a screen shot of the DEV console capturing the ACTUAL code, sorry, last night was from memory.

Dev Console showing JSON with function

Hope this helps with clarification of my question.

Upvotes: 0

Views: 1498

Answers (1)

Jonathan Gagne
Jonathan Gagne

Reputation: 4379

Like this, but be sure your are doing your condition with === instead =, and putting all your brackets.

let myTest = {
    "test": {
        "trigger": "load",
        "functionName": function(){if(1 === 1){console.log('hello');} else {console.log('goodbye');}}
    }
};

myTest.test.functionName();

Upvotes: 1

Related Questions