我正在网站上将女巫页面内容存储到mongoDB中。我不确定如何进行。

首先:我将使用此数据库中的所有链接构建菜单。因此,我将所有页面存储在scope.pages变量中。

这就是在MLAB上托管的MongoDB中用于开发的页面的外观。

{
    "_id": {
        "$oid": "58803eb7f36d2842fdb4aed0"
    },
    "name": "index",
    "file": "index.html",
    "titre": "My title",
    "author": "Me",
    "headline": "the h1 tag content",
    "content": "the text content of my document."
}


所以现在我将数据库的内容加载到scope.pages变量中

这就是应用程序的外观。

'use strict';

var mid = angular.module('mid', [
  'ngRoute'
])


mid.controller('pageCtrl', function($scope, $http){
  $scope.pages = [];

  $http({
    method: 'GET',
    url: 'http://127.0.0.1/pages'
  })
    .then(function(pages) {
      $scope.pages = pages.data;
   })
    .catch(function(errRes) {
      // Handle errRess
  });
});


这里的GET方法实际上是从节点服务器中调用数据,看起来像这样。

app.get('/pages', function(req, res){
  //calling the function
  MongoClient.connect(url, function(err, db) {
    if(err) {
      console.log(err);
      return res.status(500).send(err);
   }
    findPage(db, function(err, pages) {
        if(err){
          res.status(500).json(err);
        }
        else{
            if(!pages){
              res.status(204).send();
              }
              else{
                  console.log(pages);
                  res.jsonp(pages);
                  }
               db.close();
               return;
            }
        });
    });
  });


因此,当我在地址栏中输入mydomain.com/pages时,我会得到所有页面。我的控制器调用此url,并将结果存储到范围中。

现在在实际的html页面中,我指的是scope.pages数组中的1个页面。

<body ng-controller="pageCtrl">
{{pages[0].name}}
</body>


由于数组的第一页是我的mongoDB中上面显示的页面,因此其结果是“索引”。

您是否可以看到我正在呼吁整个数据库填补这一范围。

我希望菜单提供指向特定页面的链接,但是我不确定该如何继续。

我的菜单看起来像这样

<div ng-repeat="page in pages" ng-cloak class="nav-item" >
<a href="#/pages/{{page.id}}">{{page.name}}</a>
</div>


我希望能够以这种方式使用某些路线。

when("/pages/:id", {templateUrl: "test2.html", controller: "pageCtrl"}).


现在一切正常。当我在地址栏中输入mydomain.com/pages/1时,我得到的是test2.html。

但是,我该如何引用地址栏中提供的此ID,以便我可以加载正确的内容并将此ID传递给我的范围,如下所示

<body ng-controller="pageCtrl">
{{pages[id].name}}
</body>


因此,我最终会在视图中拥有一个想要的页面ID

最佳答案

您可以将$routeParams提供程序注入控制器,并根据:id参数加载内容

mid.controller('pageCtrl', function($scope, $http, $routeParams){
  $scope.id = ($routeParams && $routeParams["id"]) ? $routeParams["id"] : 0;
});

09-17 12:28
查看更多