在下面的代码中,我使用javascript序列化器将数据转换为json对象。如何使用$ http.get将json对象提取到名为 UserCntrl 的控制器,以便以后可以在ng-repeat中使用它?
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUserDetails()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("select UserID=id,Username=username,Mail=email from users", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
和ul持有ng-repeat
<ul>
<li ng-repeat="item in items">
{{item.Username}}
</li>
</ul>
答案 0 :(得分:1)
你可能需要调整一些东西,但这应该有效。我将您的http请求抽象到工厂,以便您可以将它与任何控制器一起使用。
app(you have to adjust this to your app).factory('userFactory', function ($http) {
var factory = {};
factory.get = function () {
return $http.get('your_rest_url', {}).then(function (resp) {
console.log('Success', resp);
}, function (err) {
console.error('ERR', err);
});
};
});
var UsrCtrl = function ($scope, userFactory) {
$scope.items = userFactory.get();
};