1

I am trying to pass some values from express NodeJS server to AngularJS controller variable. Here is the code snippet....

Server

app.post('/run-engine', function(req, res){
  console.log(req)

  res.writeHead(200, {'Content-Type': 'text/html'});

  fs.readFile('index.html', 'utf-8', function(err, content) {
    if (err) {
        res.end('error occurred');
        return;
    }
    var reconData = 'some temp';  //here I assign temp variable with needed value

    var renderedHtml = ejs.render(content, {data: reconData})
    res.end(renderedHtml);
  });

});

HTML code snippet

<section class="mdl-layout__tab-panel tab2" id="scroll-tab-2">
  <div class="page-content">
    <h1>This is Tab2</h1> Data: <%= data %>
    <form method='post' action='run-engine' enctype="multipart/form-data">
      <input type='file' name='fileUploaded'></input>
      <input type='submit'></input>
    </form>
  </div>
</section>

In the html page, I could see the value of "reconData" (which is rendered by 'data' in the content from server post method).

I want the same 'reconData' to be assigned as scope variable (engineData) in angularjs controller but I am unable to do so... Angular js controller code snippet

var myApp1 = angular.module('msnapp',[]);
myApp1.controller("MsnController", function($scope, $http) {
  $scope.engineData = ?? //this needs to be equal to reconData from server side
});

How do I get the engineData to be assigned as 'reconData' from server?

1 Answer 1

1

Try this

var myApp1 = angular.module('msnapp',[]);
myApp1.controller("MsnController", function($scope, $http) {

    $http({ method: 'POST',
            url: '/run-engine'
         }).then(function (response){
            $scope.engineData = response.data;
         }, function (error) {});

});
Sign up to request clarification or add additional context in comments.

6 Comments

'response' is entire html body
@Jay Yeah it is. I updated it to pull just the data ... like the docs say $http
But how can I get only 'reconData' so that I can use the value into the html page. I need to bind the value into angular controller variable. The html body is used that variable. As I show, in HTML I can use the value of reconData directly (through 'data' variable) but I need it in angular controller.
Sorry, I did not check response.data part. In that case I am getting undefined.
Dude just send it! Create another path in your express server that responds with res.json(reconData) instead of the compiled HTML.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.