1

I created a service to get a data from the database. The service doesn't populate the drop down

the value in response data is: [{"ID":1,"Name":"Name1"},{"ID":2,"Name":"Name2"}]

html

<md-input-container flex>
            <md-select ng-model="selected.topic" required>
                <md-option ng-repeat="topic in topics" value="{{topic.ID}}">{{topic.Name}}</md-option>
            </md-select>
        </md-input-container>

javascript controller

$scope.topics = getTopicsService.getTopics(baseUrl);

Service:

MyApp.factory('getTopicsService', function ($http) {
    return {
        getTopics: function (baseUrl)
        {
            return $http.post(baseUrl + 'Admin/getTopics').then(function (response) {
                return $.parseJSON(response.data);
            });
        }
    }
});
2
  • $scope.topics, what is the value for it ? check using console.log($scope.topics) whether scope has value or not? Commented Dec 8, 2016 at 12:17
  • have you tried the solution in the answer? Should work fine Commented Dec 8, 2016 at 12:32

2 Answers 2

1

Hmmm, try restructtruing your promise handling a little bit.

Service:

MyApp.factory('getTopicsService', function ($http) {
    return {
        getTopics: function (baseUrl)
        {
            return $http.post(baseUrl + 'Admin/getTopics');
        }
    }
});

Controller:

getTopicsService.getTopics(baseUrl).then(function(response) {
    $scope.topics = $.parseJSON(response.data);
});

Now it's a bit easier to debug the problem. If it is still not working:

  1. Check that you are getting the correct response in your http callback. Validate the data comes back in the expected structure.
  2. Make sure your controller and template are setup correctly so the template can access you controller's scope variables (test by just logging a scope variable as an angular expression in the template).

Edit 1: The reason your solution didn't work is because you are returning the $http call itself from the service method getTopics. Your service function returns BEFORE the promise itself has been resolved. Hence you are binding the $http request object itself onto your scope variable and not the response of the request.

By adding response.data to your scope variable in the callback of your http request you are making sure the scope variable is set AFTER your promise is returned.

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

1 Comment

Your solution worked. Could you please explain why I can not parseJSON in the service
0

You need to assign value to your scope variable like this,

getTopicsService.getTopics(baseUrl).then(function(resp){ $scope.topics = resp.data; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.