Okay, so I've searched around far and wide and gotten some help. Not the least from this SO answer: https://stackoverflow.com/a/24657665/1223463
But here's where I stand:
I get the data back from the Webmethod, and am able to display it with a simple {{data}}
on the page. However, nothing displays when I try to loop through the data (it consists of two JSON objects), and referencing their data keys.
Javascript:
angular.module("myApp", [])
.controller("MyController", function ($scope, $http) {
$scope.data = [];
$scope.getData = function (item, event) {
$http.post('NGTest.aspx/GetGroups', { data: {} })
.success(function (data, status, headers, config) {
$scope.data = data.d;
});
};
}).config(function ($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
HTML:
<body ng-app="myApp">
<div ng-controller="MyController" >
<button ng-click="getData(item, $event)">Get data</button>
<br/>
{{data}}
<div ng-repeat="d in data">
{{d.ID}} a row
</div>
</div>
</body>
Code behind:
[WebMethod(EnableSession = true)]
public static string GetGroups()
{
return @"[{
'ID': 1568,
'Orgno': '282-1'
}, {
'ID': 1569,
'Orgno': '8925-2'
}]";
}
So, when I press the button, I get the data displayed as: [{ 'ID': 1568, 'Orgno': '282-1' }, { 'ID': 1569, 'Orgno': '8925-2' }]
plain and simple. But the ng-repeat part yields no code.
Here's a fiddle with seemingly the same thing: http://jsfiddle.net/eurythmech/t9jzbm06/
The one thing I can see is different between them is that in the fiddle, the JSON data is supplied without quotes surrounding it.
Is this what I need to fix, somehow? If so, how?
It seems that your data are returned as a string and not as an object. You can add an eval in your $http call :
$scope.getData = function (item, event) {
$http.post('NGTest.aspx/GetGroups', { data: {} })
.success(function (data, status, headers, config) {
$scope.data = eval(data.d);
});
};
A better way would be to return an Array of objects in your GetGroups method, so ASP.NET will serialize it for you. More infos right there WebMethod returning JSON but the response obj in my $.ajax() callback is only a string
One more thing, as you said, JSON must use double quotes for strings (check http://www.json.org/ )