2017-02-28 48 views
3

所以我在GitHub上找到了练习Spring Boot项目(https://github.com/spring-projects/spring-boot)。该应用程序允许用户创建一个项目列表及其描述;还有删除列表中的项目的功能。该项目尝试使用AngularJS将自己暴露于SPA(单页应用程序)。AngularJS:添加依赖关系(内联阵列vs注入)

该代码向使用注入的定义的控制器和工厂添加依赖项。这里的所谓“controller.js”的示例类使用这个实现:

var AppController = function($scope, Item) { 
    Item.query(function(response) { 
     $scope.items = response ? response : []; 
    }); 

    $scope.addItem = function(description) { 
     new Item({ 
     description: description, 
     checked: false 
     }).$save(function(item) { 
     $scope.items.push(item); 
     }); 
     $scope.newItem = ""; 
    }; 

    $scope.updateItem = function(item) { 
     item.$update(); 
    }; 

    $scope.deleteItem = function(item) { 
     item.$remove(function() { 
     $scope.items.splice($scope.items.indexOf(item), 1); 
     }); 
    }; 
    }; 

    AppController.$inject = ['$scope', 'Item']; 
    angular.module("myApp.controllers").controller("AppController", AppController); 

现在(纠正我,如果我错了)之外,还有两种方法可以依赖添加到控制器和工厂:

  1. 内嵌阵列
  2. 隐射出

我的观点是,我可以带着所有的依赖注入的应用和重写代码所在的C ontroller和工厂定义将使用Inline Array方法添加其依赖关系。这里是相同的“controller.js”,但使用内联数组:

angular.module("myApp.controllerModule").controller("AppController", ['$scope', 'Item', function($scope, Item){ 
Item.query(function(response) { 
    $scope.items = response ? response : []; 
}); 

$scope.addItem = function(description) { 
    new Item({ 
     description: description, 
     checked: false 
    }).$save(function(item) { 
     $scope.items.push(item); 
    }); 
    $scope.newItem = ""; 
}; 

$scope.updateItem = function(item) { 
    item.$update(); 
}; 

$scope.deleteItem = function(item) { 
    item.$remove(function() { 
     $scope.items.splice($scope.items.indexOf(item), 1); 
    }); 
}; }]); 

当我试图这样做,我的代码不会像原来的代码工作。我不知道它是否是一个语法错误,或者是否在不同风格的应用程序中有一些重要的区别。谁能告诉我为什么这不起作用?

+0

如果你定义'我的代码不能像原始代码那样工作',这将会很有帮助。 – lealceldeiro

+0

注入依赖关系有三种方法:内联数组注释,'$ inject'属性注释和隐式注释。前两个是缩小安全。最后一个不是。有关更多信息,请参阅[AngularJS开发人员指南 - 依赖注入](https://docs.angularjs.org/guide/di)。 – georgeawg

回答

0

我可以在两个代码示例中看到的唯一区别是模块的名称。由于您没有提供错误消息,因此我假设您在所有应注入模块的文件中都没有将myApp.controllers更改为myApp.controllerModule

0

您可以通过参数名称ng-annotate自动生成这些注释。这是大多数项目应该使用的。手动复制依赖关系不太实际。

+1

是这样吗?我使用'$ inject'符号和缩小的代码,它的作用就像魅力一样。你是指任何特殊的缩小过程? – lealceldeiro

+0

你说得对。这两种方式都有效,但仍建议使用ng-annotate。更正了答案。 –