将值从Express NodeJS传递到AngularJS控制器变量

时间:2016-05-31 21:02:00

标签: html angularjs node.js express

我正在尝试将一些值从快速NodeJS服务器传递给AngularJS控制器变量。这是代码片段....

服务器

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>

在html页面中,我可以看到“reconData”的值(由服务器post方法中的内容中的'data'呈现)。

我想在angularjs控制器中将相同的'reconData'指定为范围变量(engineData),但我无法这样做... Angular js控制器代码段

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

如何将engineData从服务器分配为'reconData'?

1 个答案:

答案 0 :(得分:1)

试试这个

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) {});

});
相关问题