Pindakaas
Pindakaas

Reputation: 4439

webapi call from angular js to controller is not working

Just started trying out angular js. I have setup the standard asp.net mvc api controller:

public class ValuesController : ApiController
{
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
}

I am trying to get those values in my listbox:

<div ng-controller="myctrl">
        <select ng-model="selectedValue" ng-options="val for val in getData()">
            <option value="">Select</option>
        </select>
</div>

Using this script:

 var app = angular.module('app', []);
 app.controller('myctrl', function ($scope, $http) {
     $scope.getData = $http.get('/api/values').then(function (data) {
         return data;
     });
 });

When I run this it does not populate the listbox and jsfiddle:http://jsfiddle.net/dingen2010/t3eXj/

Upvotes: 2

Views: 1361

Answers (2)

Chandermani
Chandermani

Reputation: 42669

Promise unwrapping does not happen in AnuglarJS 1.2.x version. I believe your code should do something like

     $http.get('/api/values').then(function (data) {
         $scope.values=data;
     });

And in your html

        <select ng-model="selectedValue" ng-options="val for val in values">
            <option value="">Select</option>
        </select>

Upvotes: 2

miqh
miqh

Reputation: 3664

In your use case above, had you of chosen to chain your get call with the success method instead, then data would be what you expect it to be (i.e. the data returned by your API).

But, since you are using the then method, the argument fed to the callback is actually a promise object, and the data you want can be accessed using the data property.

 $scope.getData = $http.get('/api/values').then(function (promise) {
     return promise.data;
 });

Upvotes: 0

Related Questions