2016-02-03 27 views
0

我是新的角度,我需要幫助來調用一個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. 
    }); 

}); 

它允許填寫選擇的模式窗體 modal form

此選擇上確認按鈕每次用戶點擊的變化(選擇顯示的免費用戶),所以我雖然創建一個服務用上面的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> 

我如何更新我的選擇值感謝

回答

1

首先,改變你的服務,所以它有一個函數來調用:

app.service("freeUserService",['$http', function($http){ 
    var service = this; 

    service.getusers = getusers; 

    function getusers() { 
     var url = "your url gets here"; 
     return $http.get(url); 
    } 

}]); 

然後,像ARNAB說,你需要改變你的控制器:

app.controller('freeUserController', ['freeUserService', '$scope', function(freeUserService, '$scope') { 

    $scope.fetchusers = function() { 
     freeUserService.getusers() 
        .then(handleGetUsers) 
        .catch(handleErrors); 
    } 

    function handleGetUsers(result){ 
     //This is a promise, because $http only does asynchronous calls. No 
     //need to wrap this in a jquery thingy. 

     //As soon as the async function is resolved, the result data is put 
     // on your scope. I used $scope.users on purpose, because of your 
     //html 
     $scope.users = result.data; 
    } 

    function handleErrors(error){ 
     console.log(error); 
    } 

}]); 

正如您所見,我已將「可變」用戶放在範圍內。我這樣做的目的是因爲你的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> 

選擇查找稱爲用戶的變量的範圍。由於變量用戶在您的html上,角度會自動監視變量的變化。

我從你的問題中瞭解到,每次http調用完成後,你會得到另一個結果,對吧?所以Angular會自動監控一個變化,並將結果反映到您選擇的元素上。如果您對更多信息感興趣,請閱讀this。我還建議遵循'從角度教程開始',因爲從你的問題出發,我認爲你錯過了Angular的基礎知識。

您需要做的最後一步(我認爲,如果我理解您的問題)將$ http函數綁定到您的HTML。有一個你可以使用的「ng-click」指令。在你的情況下,該按鈕,然後可能看起來像這樣:

<button ng-click="fetchusers()" type="submit">Get me new users</button> 

正如你所看到的,我用的是$ scope.fetchusers()函數在NG-點擊指令,將至極進行新的HTTP調用,獲得新的用途(當然,如果http調用每次調用它時都會獲得新用戶)。

修改後的代碼here

您可以使用ng-init指令來初始化該值。我會更新我的plunker,以便你可以看到ng-init是如何工作的。你應該把它設置在ng-controller旁邊。 ng-init將進行第一次調用並從一開始就給你提供數據。然後每次按下按鈕,新數據都會出現,並且您的選擇將被更新。我已經更新了這個龐然大物。我已經添加了我自己的Web服務之一。請注意,我的網絡服務是在一個免費的heroku帳戶上。如果等待時間過長,heroku應用程序將進入睡眠模式,並且第一次數據調用將超時。

關於多個異步調用:

角承諾可以鏈接!因此,您可以執行一次異步調用(例如對數據庫進行發佈),等待它完成,然後獲取更新的數據。在您的服務中,您可以這樣做:

function getUsers(parameters) { 
     var posturl = "url to post to"; 


     return $http.post(url, data) //the update, it returns a promise 
        .then(handlePost) 
        .catch(handleError); 
    } 

function handlePost(result){ 
     //the $http.get will only be executed after the previous promise has been 
     //resolved! 
     var geturl = "url to get data from"; 
     return $http.get(url); // this is the second asynchronous call 
} 

鏈接承諾是一個很好的做法。對此使用jQuery ajax調用將是不好的做法。

+0

我試着用你的代碼,但我檢索未知的提供者:$ scopeProvider < - $範圍< - freeUserService,我已經從函數中移除了''(freeUserService,'$ scope')。 對於第二個問題我知道數據綁定,但我必須調用這個http函數,因爲如果我不調用函數,Angularjs不能知道返回的值發生了改變 – luca

+0

現在它不能返回異常,但函數僅在點擊按鈕時調用?因爲我在users.length上有一個ng顯示,即使在頁面加載 – luca

+0

,我也需要這個值,謝謝,我明白它的作用。只有一個小問題:如果我使用ng單擊提交按鈕,在與按鈕關聯的指令完成之前調用它(它調用Rest Web服務寫入數據庫),因此它檢索未更新的數據。所以我已經連接了ng-click來打開模式按鈕,但是它顯示了模式之後獲得了數組的長度,所以用戶看到了模態變化。唯一的解決方法是在JQuery成功調用(關聯到提交按鈕)內調用fetch users(),這有可能嗎? – luca

0

進樣freeUserService到控制器freeUserController到ATLEAST調用來自您的控制器的服務,如:

app.controller('freeUserController', ['freeUserService', function(freeUserService) { 
    freeUserService(); 

}]); 

否則,你這樣寫:

var app = angular.module('myApp',[]); 
app.controller('freeUserController', ['freeUserService', function($scope, freeUserService) { 

    var promise = freeUserService(); 
    promise.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. 
    }); 

    // And bind the users variable in your template 

}]); 

app.service("freeUserService", ['$http', function($http){ 


    return $http({ 
     method: 'GET', 
     url: 'users' // Proper url to your api 
    }); 

}]); 
+0

它給出錯誤:$ injector:modulerr – luca

+0

使用下面的代碼。看看是否有效。 –

+0

實際上沒有用於服務的$ scope。如果你製造一個撬棍,我可以看到。 –