我想将工厂服务中的列表对象返回给控制器。列表对象包含数据,当我从服务中返回它时,但是当控件到达调用控制器时,列表变为空(值丢失)。AngularJs中从工厂服务到控制器的返回值丢失
我所说的NG-变化= “搜索()” 上的文字输入
下面的代码:
factoryservice.js
app.factory('newService', ['$http', '$q','$filter', function ($http, $q, $filter)
{
var ServiceFactory = {};
var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toString().toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};
var _search = function (Items, data, sortingOrder, query, reverse) {
Items = $filter('filter')(data, function (item) {
for (var attr in item) {
if (angular.isUndefined(item[attr]) || item[attr] === null)
continue;
if (searchMatch(item[attr], query))
return true;
}
return false;
});
// take care of the sorting order
if (sortingOrder !== '') {
Items = $filter('orderBy')(Items, sortingOrder, reverse);
}
return Items;
};
ServiceFactory.search = _search;
return ServiceFactory;
}]);
这里, “回归项目” 在搜索方法具有适当的值。
controller.js
app.controller('mycontroller', ['$scope', '$http', '$filter', 'Service', function ($scope, $http, $filter, Service) {
var sortingOrder = 'Site';
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.Items = [];
$scope.Data = function() {
$scope.loading = true;
$http({
url: "http://localhost:50100/api/mycontroller",
dataType: 'json',
method: 'GET',
data: '', // data:'', for input parameters, create a small entity class and assign it
headers: {
"Content-Type": "application/json"
// "Content-Type": 'application/x-www-form-urlencoded'
}
}).success(function (response) {
$scope.Data = response;
$scope.Items = $scope.Data;
})
.error(function (error) {
alert(error);
})
.finally(function() {
$scope.loading = false;
});
}
$scope.search = function() {
return Service.search($scope.Items, $scope.Data, $scope.sortingOrder, $scope.query, $scope.reverse);
};
}]);
这里,$ scope.search包含空值(数据被丢在这里)。
我是angularJS的新手,希望有人能帮助我解决这个问题。提前致谢。
你能创建一个plunker或jsfiddle来演示这个 – gh9
'$ scope.search'应该永远不会包含数据吗?这只是一个功能。它应该返回数据。您是否曾尝试在工厂中使用制动点进行调试? –
是的Bjorn,我将Service.search分配给$ scope.search,它现在似乎正在工作。 – Desparado