如何在组合angularjs和mongodb时编辑数据



我是AngularJs和MongoDb世界的初学者(我今天开始学习!!

实际上,我正在尝试做一些非常基本的事情:显示记录列表,带有添加按钮和每条记录的编辑链接。

我正在使用这个库 https://github.com/pkozlowski-opensource/angularjs-mongolab 连接到mongoweb。

实际上,当我

尝试添加记录时,我的数据会显示出来,但是当我尝试显示编辑表单时,它就可以工作了!

这是我的索引.html文件,其中我使用用于添加记录的表单和编辑链接显示数据:

<div ng-controller="AppCtrl">
    <ul>
        <li ng-repeat="team in teams">
            {{team.name}} 
            {{team.description}}
            <a href="edit.html?id={{team._id.$oid}}">edit</a>
        </li>
    </ul>
    <form ng-submit="addTeam()">
        <input type="text" ng-model="team.name"  size="30" placeholder="add new team here">
        <input type="text" ng-model="team.description"  size="30" placeholder="add new team here">
        <input class="btn-primary" type="submit" value="add">
      </form>
</div>

这是我的编辑.html代码,它显示一个编辑表单:

<div ng-controller="EditCtrl">
    <form ng-submit="editTeam()">
        <input type="text" name="name" ng-model="team.name"  size="30" placeholder="edit team here">
        <input type="text" name="description" ng-model="team.description"  size="30" placeholder="edit team here">
        <input class="btn-primary" type="submit" value="validate edit">
      </form>
</div>

最后是我的js代码:

var app = angular.module('app', ['mongolabResource']);
app.constant('API_KEY', '____________________________');
app.constant('DB_NAME', 'groups');
app.factory('Teams', function ($mongolabResource) {
    return $mongolabResource('teams');
});
app.controller('AppCtrl', function ($scope, Teams) {
    $scope.teams = Teams.query();
    $scope.addTeam = function() {
        varteam = {
            name: $scope.team.name, 
            description: $scope.team.description
        };
        $scope.teams.push(varteam);
        Teams.save($scope.team);
        $scope.team.name = '';
        $scope.team.description = '';
    };
});
app.controller('EditCtrl', function ($scope, Teams) {
    //????????
});

我的AppCtrl工作得很好,它完美地显示数据w添加记录。

现在我想添加用于编辑的 js 代码,但我什至不知道从哪里开始? 如何获取 URL 中的 id 参数? 如何告诉视图从数据库中的值中填写表单字段?最后,我如何更新数据库。

我知道我问了很多问题,但我真的很迷茫!谢谢

当然有很多可能的解决方案。

一种解决方案是使用 angularjs 路由。有关教程,请参阅 http://docs.angularjs.org/tutorial/step_07。

基本上用以下内容替换您的 ul 列表:

<ul>
    <li ng-repeat="team in teams">
        {{team.name}} 
        {{team.description}}
        <a href="#teams/{{team._id.$oid}}">edit</a>
    </li>
</ul>

然后,您可以创建响应您的网址的路由:

yourApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/teams', {
        templateUrl: 'partials/team-list.html',
        controller: 'TeamListCtrl'
      }).
      when('/teams/:teamId', {
        templateUrl: 'partials/team-detail.html',
        controller: 'TeamDetailCtrl'
      }).
      otherwise({
        redirectTo: '/teams'
      });
  }]);

通过这种方式,您可以从详细控制器(将取代您的 EditCtrl)访问 id 参数: $routeParams.teamId

无论如何,我建议好好研究所有教程以获得更好的概述。

最新更新