所以我在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);
现在(纠正我,如果我错了)之外,还有两种方法可以依赖添加到控制器和工厂:
- 内嵌阵列
- 隐射出
我的观点是,我可以带着所有的依赖注入的应用和重写代码所在的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);
});
}; }]);
当我试图这样做,我的代码不会像原来的代码工作。我不知道它是否是一个语法错误,或者是否在不同风格的应用程序中有一些重要的区别。谁能告诉我为什么这不起作用?
如果你定义'我的代码不能像原始代码那样工作',这将会很有帮助。 – lealceldeiro
注入依赖关系有三种方法:内联数组注释,'$ inject'属性注释和隐式注释。前两个是缩小安全。最后一个不是。有关更多信息,请参阅[AngularJS开发人员指南 - 依赖注入](https://docs.angularjs.org/guide/di)。 – georgeawg