我是AngularJS的新手。我似乎無法獲得$ http的工作。我有以下工廠:
app.factory('employeeFactory', function ($http) {
var factory = {};
// get data form controller
var employees = [];
var Url = "../../../Employee/GetEmployees";
// this does not work ----------------------------
$http.get(Url, { params: { term: 'Step' }}).
success(function (response, status, headers, config) {
employees = response.data
}).
error(function (response, status, headers, config) {
alert(error);
});
// this works using JQuery ajax ----------------------------
$.ajax({
url: Url,
data: { term: 'Step' },
dataType: "json",
type: "GET",
error: function (request, status, error) {
alert(error);
},
success: function (response) {
$.each(response.data, function (i, obj) {
employees.push({ EmployeeName: obj.EmployeeName, EmployeeNumber: obj.EmployeeNumber });
});
}
});
factory.getEmployees = function() {
return employees
};
return factory;
});
而下面的控制器:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
init();
function init() {
$scope.employees = employeeFactory.getEmployees();
}
});
AJAX調用在工廠工作,但是$ HTTPS不(兩者都是在工廠裏,我只是註釋掉其中一個或另一個測試)。我看着在谷歌Chrome瀏覽器開發工具和兩個調用相同的格式返回數據,但$ HTTP數據沒有被綁定到HTML:
<div class="container">
<h4>This is view 1</h4>
Type a name to filter: <input type="text" data-ng-model="employeeSearch" />
<ul>
<li data-ng-repeat="employee in employees | filter:employeeSearch | orderBy:'EmployeeName'">{{ employee.EmployeeName }} - {{ employee.EmployeeNumber }}</li>
</ul>
</div>
這裏是格式工廠返回了兩個電話:
{data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
0: {EmployeeNumber:123456, EmployeeName:Johnson,Bob}
EmployeeName: "Johnson,Bob"
EmployeeNumber: "123456"
我不明白爲什麼,當兩個調用都以相同的格式將數據返回給視圖時,綁定不會發生在$ http方法中。任何幫助表示讚賞
你能保證AJAX調用有你'getEmployees'之前已經完成?我不確定這兩者之間爲什麼會有所不同,但據我所知,您的員工類別中沒有任何內容可以保證數據先被讀取。 – Rup 2014-10-29 13:41:03