无法从angular到我的nodejs获取值

时间:2016-09-30 08:38:45

标签: angularjs node.js

我的想法是将数据从我的html发送到角度脚本中的函数,该函数又调用一个计算某些值的节点脚本,使用自身的函数生成结果,并以json响应的形式返回值角色剧本。

HTML

<div ng-app="myApp" ng-controller="myController" ng-init='isFocused=true'>
    <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
        <input width="100%" type="text" class="form-control" id="operand1" name="operand1" style="height:50px; font-size:32px" ng-model="operand1" ng-focus=' isFocused="operand1" ' autofocus>
    </div>

    <div class="col-lg-2 col-md-8 col-sm-12 col-xs-12 text-center" style="font-size:32px">
        {{op}}
    </div>

    <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
        <input width="100%" type="text" class="form-control" style="height:50px; font-size:32px"  ng-model="operand2" ng-focus=' isFocused="operand2" ' id="operand2" name="operand2" autofocus>
    </div>


</div>


<div class="col-lg-5">

    <div class="row">

        <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 eqProps text-center"> = </div>

        <div class="col-lg-9 col-md-9 col-sm-12 col-xs-12"style="font-size:32px" ng-model="output">
            {{output}}
        </div>
    </div>

角度剧本

var myApp = angular.module('myApp', []);

 myApp.controller('myController', function($scope) {

   $scope.operators = {
     '+': add,
     '-': sub,
     '*': mul,
     '/': div
   };
   $scope.op = '+';
   $scope.calc = calc;


  $scope.submit = function() {

    $http({
      method : "POST",
      url : '/calculator',
      data : {
        "answer" : $scope.answer
      }
    }).success(function(data) {

      $scope.output = $scope.operand1 + $scope.operand2;

    }).error(function(error) {

      $scope.output = 'Invalid Input';

    });

  };

});

/ calculator映射到./routes/calculator.compute

calculator.js

exports.compute = function(req, res){

    var operand1 = req.body.operand1;
    var operand2 = req.body.operand2;
    var operator = req.body.operator;


    var json_responses;

            json_responses = {"answer" : operand1+operand2};
            res.send(json_responses)

};

真正的问题是{{output}}不会产生计算器中计算的输出.js

2 个答案:

答案 0 :(得分:2)

您没有将正确的数据发送到nodejs。

$scope.submit = function() {

    $http({
      method : "POST",
      url : '/calculator',
      data : {
        "operand1" : $scope.operand1,
        "operand2" : $scope.operand2,
        "operator" : $scope.op
      }
    }).success(function(data) {

      $scope.output = data.answer;

    }).error(function(error) {

      $scope.output = 'Invalid Input';

    });

  };

答案 1 :(得分:0)

我认为您需要在$http {控制器中注入myApp.controller('myController', function($scope, $http)并确保您已在html中注入所有必需的j。

我正在粘贴从网址获取数据的代码,我可能对您有用。

function functionName() {
            $http.get('URL').success(function (response) {
                $scope.variableName = response;
            })
        }