我被卡住了,任何人都可以帮助我。这是代码。我正在编写grabData服务以从URL获取数据。然后在控制器firstcontroller中,我正在根据搜索框过滤数据:这是代码:
.factory("grabData",['$http',function($http){
return{
showData:function(){
return $http.get("/http://localhost:5555/sampleData.json");
}
}
}])
.controller('firstController',function($scope, $filter,grabData) {
grabData.showData().success(function(data){
$scope.items = data;
$scope.items1 = $scope.items;
$scope.$watch('search', function(val){
$scope.items = $filter('filter')($scope.items1, val);
});
}
HTML代码是: <div ng-controller="firstController"> <input type="text" ng-model="search"> </div>
谁能帮我在下一个控制器中显示$ scope.items:
.controller('secondcontroller',function($scope){
// Here I want to use $scope.items , from first controller
})
.controller('thirdcontroller',function($scope){
// Here I want to use $scope.items , from first controller
})
.controller('fourthcontroller',function($scope){
// Here I want to use $scope.items , from first controller
})
谁能帮助解决这个问题。
这样写你的服务,
.service("grabData",['$http', '$q', function($http, $q){
var sampleData = null;
var filteredData = null;
this.showData = function () {
var deferred = $q.defer();
if(sampleData!=null){
//if data has already been fetched from server before, serve it
deferred.resolve(sampleData)
}
else {
//else, fetch the data from server, and store it for future use
$http.get("/http://localhost:5555/sampleData.json").then(function(res){
sampleData = res.data;
deferred.resolve(sampleData);
})
}
return deferred.promise;
};
//call this from controller1, inside your watch
this.setFilteredData = function(data){
filteredData = data;
};
//call this from other 2 controllers
this.getFilteredData = function(){
return filteredData;
};
}])
然后像这样修改您的控制器,
.controller('secondcontroller',function($scope, grabData){
// do whatever you want to do with grabData
//use that "grabData.showData().success" pattern as it is still a promise
})
.controller('thirdcontroller',function($scope, grabData){
// do whatever you want to do with grabData
// call grabData.getFilteredData() from here
})
.controller('fourthcontroller',function($scope, grabData){
// do whatever you want to do with grabData
// call grabData.getFilteredData() from here
})
希望能帮助到你。如有疑问,请在评论中提问。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句