user1206480
user1206480

Reputation: 1858

Applying ajax data to angularjs select

Is this even possible with jquery? My javascript code works in terms of returning data with the get statement, and after debugging I verified that the uploadCategories did indeed contain the requested objects, but for whatever reason they are not being rendered to the select tag. What am I missing here?

Javascript:

var uploadController = function($scope) {

// upload category array
$scope.uploadCategories = [];
$scope.category = "";

// get categories
$.get('/api/Upload/UploadCategories', function(data) {

    // update array
    $scope.uploadCategories = [];
    $.each(data, function(i, item) {
        $scope.uploadCategories.push({
            Id: item.Id,
            Category: item.Category
        });

        // set active category
        $scope.category = $scope.uploadCategories[0].Category;

    });
}, "json");
};

HTML:

<form class="text-center" action="/Upload/AdminUpload" method="post" 
  data-ng-controller="uploadController">

<fieldset class="form-group" style="display: inline-block;">
    <legend>File Info</legend>

    <!--Upload Category-->
    <div class="form-group">
        <label for="catId">Category</label>
        <select id="catId" ng-model="category" 
                ng-options="c.Category for c in uploadCategories"></select>
    </div>


    <button type="submit" formenctype="multipart/form-data">Upload</button>
</fieldset>

Upvotes: 0

Views: 110

Answers (1)

kgautron
kgautron

Reputation: 8263

i think you need to call the $scope.$digest() function after setting the category. This makes angularJS refresh the view from the model. It is needed because your callback is in JQuery, so angular does not call the digest automatically, whereas if you use angular services instead :

$http.get('/api/Upload/UploadCategories').success(function(data){..});

the digest is implicitly be called at the end, so the refresh is automatic.

A more conventionnal way than calling the digest (but equivalent), is surrounding your callback code in a $scope.apply(function(){});, this executes your code and then calls digest.

But still the better way would be to use angular's $http.get() as it comes from the box.

Upvotes: 1

Related Questions