如何显示来自输入框的信息

时间:2018-10-10 22:12:10

标签: javascript html angularjs

我正在尝试更多地学习如何使用angular和javascript。请让我知道我在做什么错。

当我在文本框中输入内容时,它应显示

  

“你好{name},你想玩游戏吗?

它显示没有输入的字符串。

另外,当我运行它时,它会显示

  

对象对象

(function (app) {
var JakesController = function ($scope, $http) {
$scope.JakesSampleModel = {name: ' '};
$scope.theSampleReturn = null;

var sendResponseData = function (response) {
        if (response.data.error) {
           console.log(data);
        }
        else {
            $scope.theSampleReturn = response.data;
        }
    };

    var sendResponseError = function (data) {
        console.log(data);
    }

    $scope.senddata = function (params) {
        return $http({
            method: 'post',
            url: '/home/servercall',
            data: params
        })
            .then(sendResponseData)
            .catch(sendResponseError);
    };
};

app.controller("JakesController",['$scope', '$http', JakesController]);

}(angular.module("JakesFirstApp")));

这是HTML:

<div id="OutterDiv" ng-controller="JakesController" ng-app="JakesFirstApp">
<div id="JakesButton" class="button" ng-click="senddata()">Submit</div>
<input type="text" id="JakesTextBox" ng-model="theSampleReturn" />
{{theSampleReturn.result}}

Json结果:

public JsonResult servercall(string name)
    {
        return Json(new { result = $"Hello {name}, Would you like to play a game?" }, JsonRequestBehavior.AllowGet);
    }

2 个答案:

答案 0 :(得分:1)

在您的html中尝试使用{{theSampleReturn}}而不是{{theSampleReturn.result}},因为您似乎没有在任何地方设置theSampleReturn.result

答案 1 :(得分:0)

如果我理解您的问题正确,那么看来解决方案是像这样更新模板:

<input type="text" id="JakesTextBox" ng-model="JakesSampleModel.name" />

然后更新控制器,以在调用senddata()时将名称正确发送到服务器:

$scope.senddata = function () {

    // Construct params for post by getting data from your scope/model that's
    // wired up to your input field
    var params = { name : $scope.JakesSampleModel.name };

    return $http({
        method: 'post',
        url: '/home/servercall',
        data: params
    })
    .then(sendResponseData)
    .catch(sendResponseError);
};