0
我是Angularjs的新手,剛開始幾天回來,
我得到了一個使用$ http的代碼,工作正常。
var sampleApp = angular.module('sampleApp', []); // Define new module for our application
// Create new controller, that accepts two services $scope and $http
function SampleCtrl($scope, $http) {
$scope.date = "sample date"; // Bind data to $scope
// Define new function in scope
$scope.fetch = function() {
// Use $http service to fetch data from the PHP web service
$http.get('api.php').success(function(data) {
$scope.date = data.date; // Bind the data returned from web service to $scope
});
}
};
SampleCtrl.$inject = ['$scope', '$http']; // Ask Angular.js to inject the requested services,
sampleApp.controller('SampleCtrl', SampleCtrl); // Initialize controller in pre-defined module
========================
我想兩件事情
當我的評論行SampleCtrl.$inject = ['$scope', '$http'];
從上面的代碼,代碼仍然有效,我需要知道,爲什麼我們需要這個或當我們需要這個。
2.分離提取功能類似
function fetchData() {
// Use $http service to fetch data from the PHP web service
$http.get('api.php').success(function(data) {
$scope.date = data.date; // Bind the data returned from web service to $scope
});
return $scope;
}
// Create new controller, that accepts two services $scope and $http
function SampleCtrl($scope, $http) {
// Define new function in scope
$scope.fetch = fetchData($scope, $http);
};
對不起不能做的jsfiddle,但這裏是我從
https://www.openshift.com/blogs/how-to-use-angularjs-with-php-hosting-on-openshift
試圖在「etting Started with Angular.js
部分代碼
+1爲第三選項可將控制器......我發現一個最清晰的。 – Jorg
它主要取決於你的代碼寫作風格哪一個是最適合使用的。如果你更喜歡首先定義函數,然後通過angular.module()[component]賦值,那麼使用$ inject會更清晰。但是,如果你正在模塊[組件]內部飛行定義函數,我更喜歡括號注入 – doodeec
@doodeec,嘿謝謝,看起來你是正確的,請你澄清我的第二個疑問(2.分離獲取函數就像)。在那裏有任何錯誤 –