我正在尝试使用AngularJS
显示ajax回调之后的事件列表HTML:
<ul>
<li ng-repeat="event in events">{{ event.content }}</li>
</ul>
控制器:
app.controller("myctrl", function ($scope, mySrv) {
$scope.message = "";
$scope.events = mySrv.getEvents(26);
});
SERVICE:
app.factory('mySrv', function ($http) {
return {
getEvents: function (i_RequestID) {
$http({
method: 'POST',
url: '/Home/GetOptimizationResultEvents',
data: { RequestID: i_RequestID }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}
});
现在没有错误,但我看不到任何结果.. 我在这里做错了什么?
答案 0 :(得分:2)
app.factory('mySrv', function ($http) {
return {
getEvents: function (i_RequestID) {
$http({
method: 'POST',
url: '/Home/GetOptimizationResultEvents',
data: { RequestID: i_RequestID }
});
}
}
});
我个人更喜欢在工厂中转换我的原始数据
app.factory('mySrv', ['$q', '$http', function ($q, $http) {
return {
getEvents: function (i_RequestID) {
return $q(function(resolve, reject) {
$http({
method: 'POST',
url: '/Home/GetOptimizationResultEvents',
data: { RequestID: i_RequestID }
})
.then(function(response) {
var data = response.data;
// transforms
resolve(data);
})
.catch(function(reason) {
reject(reason);
});
});
}
}
}]);
答案 1 :(得分:0)
你的getEvents
- 函数需要返回通话的承诺:
getEvents: function (i_RequestID) {
return $http({
method: 'POST',
url: '/Home/GetOptimizationResultEvents',
data: { RequestID: i_RequestID }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
这将使getEvents
返回一个承诺,所以在你使用它的地方你会这样:
app.controller("myctrl", function ($scope, mySrv) {
$scope.message = "";
mySrv.getEvents(26).then(function(result){
$scope.events = result;
});
});
分配$scope.$apply()
$scope.events = result;
答案 2 :(得分:0)
只是在黑暗中刺伤,但你试过回复承诺吗?
app.factory('mySrv', function ($http) {
return {
getEvents: function (i_RequestID) {
return $http({
method: 'POST',
url: '/Home/GetOptimizationResultEvents',
data: { RequestID: i_RequestID }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}
});
答案 3 :(得分:-1)
试试这个
app.controller("myctrl",['$scope', 'mySrv', function ($scope, mySrv) {
$scope.message = "";
$scope.events = mySrv.getEvents(26);
}]);
还要检查正确加载的控制器和应用脚本文件