【问题标题】:CRUD with AngularJS and Play使用 AngularJS 和 Play 的 CRUD
【发布时间】:2014-10-03 11:04:47
【问题描述】:

我正在使用 AngularJS、Play Framework 和 MongoDB 构建一个新项目。我的代码基于 Typesafe Activator 的现代网络模板。目前我可以创建新对象并将它们显示在列表中。下一步是编辑一个对象,这就是我遇到的问题。

在我的类别列表中,我的表格中有以下链接:

<td><a ng-href="/#/categories/edit/{{cat.category}}">edit</a></td>

我的 app.coffee(Angular.js 路由):

angular.module('myApp.routeConfig', ['ngRoute'])
    .config ($routeProvider) ->
        $routeProvider
        .when('/categories/edit/:category', {
                templateUrl: '/assets/partials/categories/edit.html'
                controller: '/assets/javascripts/categories/EditCategoryCtrl'
            })

EditCategoryCtrl.coffee

class EditCategoryCtrl

constructor: (@$log, @$location,  @CategoryService, @category) ->
    @category = @CategoryService.findCategoryByCategory(category) // should load the category, but the constructor doesn't get invoked (see below)


editCategory: (category: String) ->
    @CategoryService.editCategory(@category)
    .then(
        (data) =>
            @category = data
            @$location.path("/categories")
        ,
        (error) =>
            @$log.error "Unable to edit Category: #{error}"
        )
controllersModule.controller('EditCategoryCtrl', EditCategoryCtrl)

我的游戏路线文件:

GET     /categories/edit/:category  @controllers.Categories.findByCategory(category: String)
PUT     /categories/edit/:category  @controllers.Categories.edit(category: String)

如上所述,我在 EditCategoryCtrl.coffee 中的构造函数没有被调用,并且在 javascript 控制台中引发了以下错误:

Error: [ng:areq] Argument '/assets/javascripts/categories/EditCategoryCtrl' is not a function, got undefined
http://errors.angularjs.org/1.2.13/ng/areq?p0=%2Fassets%2Fjavascripts%2Fcategories%2FEditCategoryCtrl&p1=not%20a                 nanunction%2C%20got%20undefined

我希望我加入了所有必要的代码(如果没有,请告诉我)。希望任何人都可以指出我正确的方向。谢谢!

编辑 我的CategoryService.coffee

findCategoryByCategory: (category) ->
        @$log.debug "findCategoryByCategory()"
        @$log.debug category
        deferred = @$q.defer()

        @$http.get("/categories/edit/:category", category)
        .success((data, status, headers) =>
                @$log.info("Successfully loaded Category - status #{status}")
                deferred.resolve(data)
            )
        .error((data, status, headers) =>
                @$log.error("Failed to load Category - status #{status}")
                deferred.reject(data);
            )
        deferred.promise

edit2

在 Valentin 的帮助下,我现在可以将类别对象加载为 JSON 并将其记录到我的控制台:

"Successfully loaded Category - status 200"
Object { category: "test", description: "test", status: Object }

但我的视图仍然没有呈现任何内容edit.html

<div ng-controller="EditCategoryCtrl as ecc"><!-- other stuff --> 
<input type="text" class="form-control" name="category" id="category" ng-model="ecc.category.category">

这似乎不起作用。问题是否可能是在异步查询完成之前呈现?如果是,我该如何防止这种情况发生?

【问题讨论】:

  • 我不是 CoffeeScript 专家,但您确定要使用类来定义控制器吗?
  • 我也不是,但同样的代码适用于我的 CreateCategoryCtrl class CreateCategoryCtrl constructor: (@$log, @$location, @CategoryService) -&gt; @$log.debug "constructing CreateCategoryController" @category = {}

标签: javascript angularjs mongodb playframework coffeescript


【解决方案1】:

category 不会被依赖注入,因为它是一个 URL 参数。

您可以从$routeParams 服务中检索它,例如:

controllersModule.controller('EditCategoryCtrl',
  ['$log', '$location', 'CategoryService', '$routeParams', '$scope',
    ($log, $location, CategoryService, $routeParams, $scope) ->
      CategoryService.findCategoryByCategory($routeParams.category)
      .then((category) ->
        $scope.category = category
      )
  ])

或在路由声明中使用resolve,例如:

$routeProvider
  .when('/categories/edit/:category', {
    templateUrl: '/assets/partials/categories/edit.html'
    controller: '/assets/javascripts/categories/EditCategoryCtrl'
    resolve: {
      category: ['$routeParams','CategoryService', ($routeParams, CategoryService) -> CategoryService.findCategoryByCategory($routeParams.category)]
    }
  })

如果findCategoryByCategory 是异步的,您很可能希望使用第二种方法。

最后,您的对象不会被渲染,因为它从未导出到$scope(见上文)。这是您的 HTML 应该是这样的:

<div ng-controller="EditCategoryCtrl"><!-- other stuff --> 
<input type="text" class="form-control" name="category" id="category" ng-model="category.category">

您真的不应该将控制器视为一个类,而是将服务和$scope 对象注入其中的函数,让您可以将 HTML 和服务与显示逻辑绑定。

【讨论】:

  • 这确实有效。至少现在我的CategoryService.findCategoryByCategory 中有正确的category,但现在我在行中得到"Error: parsed is undefined(来自JS 控制台的输出):this.$http.get("/categories/edit/:category", category).success(function(data, status, headers) {
  • 你不能这样称呼$http.get。在您的 URL 字符串中手动将 :category 替换为 category。见这里:docs.angularjs.org/api/ng/service/$http#get
  • with @$http.get("/categories/edit/" + category) 我更进一步(请参阅我对原始帖子的第二次编辑)。不幸的是,我还没到那一步。感谢您迄今为止的帮助!
  • 不幸的是我现在收到错误"Error: this.$scope is undefined。我尝试了您的两种变体,但最终总是出现此错误。
  • 那一定是我的坏 CoffeeScript。如果你愿意,我可以告诉你如何在不使用类的情况下做到这一点。
猜你喜欢
  • 2017-01-10
  • 2015-06-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多