我是新的角度,我需要幫助來調用一個http請求。 我有這個控制器從jquery調用或選擇打開呼叫Angularjs HTTP請求服務
var app = angular.module('myApp',[]);
app.controller('freeUserController', function($scope, $http) {
$http({
method: 'GET',
url: 'users'
}).then(function successCallback(response) {
$scope.users = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
此選擇上確認按鈕每次用戶點擊的變化(選擇顯示的免費用戶),所以我雖然創建一個服務用上面的http調用並使用這個或確認按鈕(或確認按鈕的內部javascript)或當用戶點擊選擇tho顯示用戶。 所以我改變角度這樣的代碼:
var app = angular.module('"modalUploadLicense"',[]);
app.controller('freeUserController', function() {
freeUserService();
});
app.service("freeUserService",function($scope, $http){
$http({
method: 'GET',
url: 'users'
}).then(function successCallback(response) {
$scope.users = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
但它給我一個錯誤,而且我不知道調用該服務在用戶列表改變的最佳途徑。 這是我的確認按鈕的javascript:
$("#createLicenseButton").click(
function() {
var form = $("#addLicenseForm");
$.ajax({
type : "POST",
url : form.attr("action"),
data : form.serialize(),
// all right with rest call
success : function(data) {
//No exception occurred
if (data.status==true){
//Also the field are right(for e.g. form value)
if(data.success==true){
//il risultato sta in data.result
//window.location.reload(true);
$('#licensesTable').load(document.URL + ' #licensesTable');
angular.element(document.getElementById('freeUserController')).scope().get();
//reload only the tag with id carsTable, so only the table
//$('#carsTable').load(document.URL + ' #carsTable');
$('#addLicenseModal').modal("hide");
notifyMessage("Your license has been created!", 'success');
}
else{
//code if there are some error into form for example
}
} else {
//code exception
$('#addLicenseModal').modal("hide");
notifyMessage("Error! Your license hasn't been created!", 'error');
}
},
//error during rest call
error : function(data) {
window.location.href = "/ATS/500";
}
});
});
而HTML選擇是:
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.username as user.username for user in users track by user.username">
</select>
我如何更新我的選擇值感謝
我試着用你的代碼,但我檢索未知的提供者:$ scopeProvider < - $範圍< - freeUserService,我已經從函數中移除了''(freeUserService,'$ scope')。 對於第二個問題我知道數據綁定,但我必須調用這個http函數,因爲如果我不調用函數,Angularjs不能知道返回的值發生了改變 – luca
現在它不能返回異常,但函數僅在點擊按鈕時調用?因爲我在users.length上有一個ng顯示,即使在頁面加載 – luca
,我也需要這個值,謝謝,我明白它的作用。只有一個小問題:如果我使用ng單擊提交按鈕,在與按鈕關聯的指令完成之前調用它(它調用Rest Web服務寫入數據庫),因此它檢索未更新的數據。所以我已經連接了ng-click來打開模式按鈕,但是它顯示了模式之後獲得了數組的長度,所以用戶看到了模態變化。唯一的解決方法是在JQuery成功調用(關聯到提交按鈕)內調用fetch users(),這有可能嗎? – luca