简体   繁体   English

ajax请求数据未加载 - Angular JS

[英]ajax request data not getting loaded - Angular JS

I am trying to populate a ListBox dynamically. 我试图动态填充ListBox。 But it's not working with ajax request. 但是它没有使用ajax请求。

Here's what I am doing. 这就是我在做什么。

My Ajax request : 我的Ajax请求:

angular.module("confessions_module").factory("Universities",function(){

    var service = {};

        service.getUniversitiesAjax=function(callback)
        {
            $.ajax({
                type:'GET',
                url:'myurl',
                success:function(e)
                {
                    universitiesList = $.parseJSON(e);
                    callback(universitiesList);
                }

            });

//                var a = [{ 'name':'asdasdsad','id':123},{ 'name':'mozi','id':123}];
 //              callback(a)
        }
    return service;
});

My Controller calling the function and populating the array: 我的Controller调用函数并填充数组:

   Universities.getUniversitiesAjax(
    function(university)
    {

        for(var i=0;i<university.length;i++)
        {
            var unii = { 'name' : university[i].name , 'id' : university[i].id };
            $scope.unis.push(unii);
        }
    }
);

My View: 我的观点:

                   <select id="dd_universities">
                        <option ng-repeat="uni in unis">{{uni.name}}</option>
                    </select>

Now there are two lines commented in My Ajax Request code. 现在, My Ajax Request代码中有两行注释。 When I uncomment those two lines , my data gets populated with no problem. 当我uncomment这两行时,我的数据填充没有问题。 But whenever I try to populate it using the ajax request code as it is happening now. 但每当我尝试使用ajax请求代码填充它时,就像现在正在发生的那样。 It does not work. 这是行不通的。 What could be the problem ? 可能是什么问题呢 ?

Your AJAX callback is executed "outside" of Angular, so even though you are changing your scope properties: 您的AJAX回调是在Angular“外部”执行的,因此即使您要更改范围属性:

$scope.unis.push(unii);

Angular will not notice these changes. Angular不会注意到这些变化。 Call $scope.$apply() after your for loop. 在你的for循环之后调用$scope.$apply() This will cause Angular to run a digest cycle , which will notice your changes and update your view(s). 这将导致Angular运行摘要周期 ,这将注意到您的更改并更新您的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM