如何在初始页面GET请求上填充$ scope

时间:2015-08-21 16:17:02

标签: javascript angularjs node.js

因此,我的页面取决于$ scope具有所有信息的事实。我在页面上有很多{{ information }}。在节点后端控制器上,我从数据库获取信息并将其发送到前端,但$ scope设置在不同的文件中。我很难解释我想要做什么。

这是我的index.js文件:

app.get('/page', function (req, res){

   var info = db.getInfo();

   res.render('page', {
      information: info
   });
});

然后该页面将呈现,但如何将信息提供给$ scope。

1 个答案:

答案 0 :(得分:0)

您在NodeJS中设置的路线需要通过$ http in angular进行访问。应使用ng-route在前端应用程序中处理URL路由。

如果你想通过服务器在有角度的$ scope中呈现页面,你必须让服务器生成角度代码才能这样做......但这只是过于复杂的事情。让角度处理检索该数据是最好的。

使用angularjs服务:

angular.module('yourApp')
  .service('pageLoader', function($http) {
    var baseUrl = ''; // this will be the url for your server. Normally    
                      // 'localhost' or something similar if it is a test 
                      //  environment

    return this.loadPage = function() {
      return $http.get(baseUrl + '/page'); 
    }
  })
  .controller('PageCtrl', function($scope, pageLoader) {
    $scope.page = null;

    $scope.loadPage = function() {
      pageLoader.loadPage().then(function(data) {
        $scope.page = data;
      })
    }
  });

这只是为了让您了解如何执行此操作。如果您进行搜索,有许多不同的$ http服务示例。

同时更改'渲染'发送'发送'在你的nodejs。

编辑:我假设您使用的是角度前端应用程序而不是某种其他模板系统。您应该发送该信息并使用angular生成包含该信息的页面。