2017-02-28 47 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。更正了答案。 –