角度和节点

时间:2018-01-09 18:44:09

标签: javascript html angularjs node.js get

我的问题是$http.get说明 - >如果主页中没有$http.get,我会"random 46"(测试正常),但如果我插入$http.get,我会获得"random {{ number }}"

我该如何解决这个问题?

-server.js
-public
    -core.js
    -index.html

server.js(节点后端)

//restful api
app.get('/api/random', function(req, res) {
    res.json({
        "text" : "4"
    });
});

//app
app.get('*', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

core.js(角度前端)

angular.module("myModule", [])
    .controller('myController', function($scope) {
        $scope.number = 46;

        $http.get('/api/random')
            .then(function successCallback(res) {
                $scope.number = res.data;
                console.log('success');
            }, function errorCallback() {
                console.log('Error');
        });
})

的index.html

<html ng-app="myModule">

<head>
    <!-- META -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->

    <title>Random number from sa-mp</title>

    <!-- SCROLLS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
    <style>
        html                    { overflow-y:scroll; }
        body                    { padding-top:50px; }
        #todo-list              { margin-bottom:30px; }
    </style>

    <!-- SPELLS -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script><!-- load angular -->
    <script src="core.js"></script>

</head>

<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="myController">
    <div class="container">

        <!-- HEADER AND TODO COUNT -->
        <div class="jumbotron text-center">
            <h1>random <span class="label label-info">{{ number }}</span></h1>
        </div>

    </div>
</body>

</html>

修改 我试过了

res.data
$scope.$apply();

res.data.text
$scope.$apply();

res.text
$scope.$apply();

但它不起作用。

编辑2:已解决

我替换了这个

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

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

并用它来设置数据

$scope.number = res.data.text;

1 个答案:

答案 0 :(得分:0)

尝试在回调的最后一行使用$ scope。$ apply()。

像:

    $http.get('/api/random')
        .then(function successCallback(res) {
            $scope.number = res.data.text;
            $scope.$apply();
            console.log('success');
        }, function errorCallback() {
            console.log('Error');
    });

如果有效。您可以在本文中了解更多相关信息:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

此外,您应该让res.data.text在您的HTML上拥有正确的值。喜欢:$scope.number = res.data.text;