页面加载时angular.js和node.js调用节点

时间:2014-04-02 18:37:20

标签: javascript node.js angularjs

我在尝试使用angular加载页面时调用节点函数,但由于某种原因,函数不会被调用。我指定了ng-app和控制器,我想我只是将api调用放在控制器构造函数中。以下是该页面的代码:

<!doctype html>

<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="landingPage">
<head>
    <!-- META -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->

    <title>my page</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="core.js"></script> 

</head>
<!-- SET THE CONTROLLER AND GET ALL GATEWAYS -->
<body ng-controller="mainController">

然后我的core.js文件位于同一目录中,该目录保存控制器具有控制器:

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

function mainController($scope, $http) {
    console.log('loading gateways');

    // when landing on the page, get all gateways and show them
    $http.get('/api/gateways')
        .success(function(data) {
            $scope.gateways = data;
            console.log('got response');
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

}

我从未见过任何日志声明......

2 个答案:

答案 0 :(得分:1)

我认为你只需要改变

function mainController($scope, $http) {
  //your code here
}

angular.module('landingPage').controller('mainController', function($scope, $http) {
   //your code here
});

让角知道控制器存在。

答案 1 :(得分:0)

尝试使用数组表示法进行依赖注入,如下所示。

angular.module('landingPage', []).controller('mainController',['$scope','$http', function($scope, $http) {
    console.log('loading gateways');

    // when landing on the page, get all gateways and show them
    $http.get('/api/gateways')
        .success(function(data) {
            $scope.gateways = data;
            console.log('got response');
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
}]);

检查Plunker。 但我建议使用工厂服务来加载外部数据,而不是将其加载到控制器中,因为您可以在不同的控制器中重复使用相同的服务。

带有工厂服务的示例代码

'use strict';
angular.module('landingPage', []).controller('mainController',['$scope','$http','gatewayService', function($scope, $http,gatewayService) {
    console.log('loading gateways');

    // when landing on the page, get all gateways and show them

    $scope.gateways = gatewayService.getData();

}]).factory('gatewayService', ['$http',function($http){
    return {
        getData: function() {
            return $http.get('/api/gateways')
              .success(function(data) {
                  return data
                  console.log('got response');
                  console.log(data);
              })
              .error(function(data) {
                  console.log('Error: ' + data);
                  return data;
              });
        }
    };
}]);

检查Plunkr