从jquery调用或选择打开调用Angularjs HTTP请求服务

时间:2016-02-03 09:18:14

标签: javascript jquery html angularjs http

我是角色的新手,我需要帮助才能调用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)或用户点击选择显示用户。 所以我改变角度代码如下:

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>

如何更新我的选择值?谢谢

2 个答案:

答案 0 :(得分: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>

select查看名为users的变量的范围。因为变量用户在你的html上,angular会自动监视变量的变化。

我从你的问题中理解的是,每次完成http调用,你都会得到另一个结果,对吧?因此Angular会自动监视更改,并在select元素上反映结果。如果对更多信息感兴趣,请阅读this。我还建议遵循“开始使用Angular教程”,因为从你的问题来看,我认为你错过了Angular的基础知识。

你需要做的最后一步(我想,如果我理解你的问题),将$ http函数绑定到你的HTML。您可以使用“ng-click”指令。在您的情况下,按钮可能如下所示:

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

正如您所看到的,我在ng-click指令中使用$ scope.fetchusers()函数,它将进行新的http调用,获得新的用途(当然,如果http调用每次调用时都会获得新用户)它)。

具有修改后的代码here的插件。

您可以使用ng-init指令初始化该值。我将更新我的plunker,以便您可以看到ng-init如何工作。您应该将其设置在ng-controller旁边。 ng-init将进行第一次调用并从头开始为您提供数据。然后,每次按下按钮,都会有新数据出现,您的选择将会更新。我已经更新了插件。我添加了一个自己的网络服务。请注意,我的网络服务是免费的heroku帐户。如果等待时间过长,heroku应用程序将进入睡眠模式,第一次数据调用将超时。

关于多个异步调用:

Angular承诺可以链接!因此,您可以执行一次异步调用(例如,对数据库执行发布操作),等待它完成,然后获取更新的数据。在您的服务中,您可以这样做:

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调用是不好的做法。

答案 1 :(得分:0)

freeUserService注入您的控制器freeUserController,以便至少从您的控制器调用该服务,例如:

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
    });

}]);