所以我在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