【问题标题】:AngularJs: doubts implementing controllerAngularJs:怀疑实现控制器
【发布时间】:2013-10-09 02:28:21
【问题描述】:

我正在测试应用程序中实现我的第一个 AngularJS 控制器,但遇到了一些困难。

我有一个从 RESTful Web 服务获取的项目列表,我正在尝试为这些项目实现基本的 CRUD 逻辑。

列表显示在itemsList.htm页面中,路由配置是:

app.config(function ($routeProvider) {
    $routeProvider
        .when('/items',
            {
                controller: 'ItemsController',
                templateUrl: 'app/Partials/itemsList.htm'
            })
        .when('/items/:itemID',
            {
                controller: 'ItemsController',
                templateUrl: 'app/Partials/editItem.htm'
            })
        .otherwise({ redirectTo: '/items' });
});

然后我有我的ItemsController:

app.controller('ItemsController', function ($scope, $routeParams, $location, itemsService) {
    $scope.status;
    $scope.items;

    getItems();

    function getItems() {
        itemsService.getItems()
            .success(function (items) {
                $scope.items = items;   
            })
            .error(function (error) {
                $scope.status = 'Unable to load items: ' + error.message;
            });
    }

    function getItem(ID) {
        // ...  
    }
}

现在我想向同一个控制器添加一个函数,该函数返回某个项目并传递其 ID 并填充 editItem.htm 页面,但我不知道我要访问此函数...

我的意思是:如何将路径 /items/:itemID 映射到此函数? 我应该在不同的控制器中实现它并更改路由配置吗?

注意我通常使用 Java 和 Spring MVC 实现我的 Web 应用程序,并且我通常为我的应用程序中的每个实体实现一个控制器(例如:ItemsController、CustomersController 等)。 AngularJs 也遵循此规则是否正确,或者还有其他一些最佳实践?

【问题讨论】:

  • 排序 $scope.$on('$routeChangeSuccess', function (scope, next, current) { var path = $location.path(); });

标签: javascript angularjs model-view-controller controller


【解决方案1】:

我的做法是实现一个ItemController,它一次只处理一个项目。同样,这取决于 html 的结构。

在任何情况下,您都需要使用 $routeParams 集合来检索所选项目的 ID。

在控制器中你可以做

if($routeParams.itemID) {
   //you got the id. call the getItem
   getItem(itemID).success(function(item) {
       $scope.item=data;
   });
}

如果您使用相同的控制器,则必须将这部分添加到 ItemsController 中,或者如果您创建新的控制器,仍需要进行相同的检查。

如果您使用现有的 ItemsController,则实现应该是这样的

 if($routeParams.itemID) {
       //same as above code
 }
 else {
     getItems();
 }

这意味着您不想在单个项目视图的范围内加载列表。

【讨论】:

  • 你的意思是:“实现一个一次只处理一个项目的ItemController”?那么实现我的控制器的正确方法应该是什么?抱歉,我对 AngularJS 完全陌生...
  • ItemsController 可用于项目列表、排序、过滤等。对于单个项目的操作可以有一个 ItemController,它可以支持单个项目的操作,例如创建、编辑、删除、更新等. 您当前对两个场景\视图使用相同的控制器。
  • 呃,好吧...我没有注意到 Items/Item 的区别... :) 这对我来说有点奇怪,在 Spring MVC 中我通常为每个实体实现一个控制器(即 ItemsController 、客户控制器等)。但是,好吧……我会听从你的建议。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-12
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 2017-10-01
  • 2016-09-06
相关资源
最近更新 更多