0

I am trying to populate a ListBox dynamically. But it's not working with ajax request.

Here's what I am doing.

My Ajax request :

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:

   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. When I uncomment those two lines , my data gets populated with no problem. But whenever I try to populate it using the ajax request code as it is happening now. It does not work. What could be the problem ?

3
  • 1
    you should be using $http instead of $.ajax otherwise you may face some problems Commented May 10, 2013 at 17:10
  • $http is provided by angular ? Commented May 10, 2013 at 17:10
  • Yeah it's an injectable service and then you can simply $http.get("myurl").success(function(){}) The largest benefit of this is that responses are digested inside of the angular framework, meaning you don't have to use $scope.$apply(). docs.angularjs.org/api/ng.$http Commented May 10, 2013 at 17:50

1 Answer 1

2

Your AJAX callback is executed "outside" of Angular, so even though you are changing your scope properties:

$scope.unis.push(unii);

Angular will not notice these changes. Call $scope.$apply() after your for loop. This will cause Angular to run a digest cycle, which will notice your changes and update your view(s).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.