我被困住了,有人可以帮助我吗?这是代码。我正在编写 grabData 服务来从 url 获取数据。然后在 Controller 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>
任何人都可以帮我在下一个 Controller 中显示 $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 ,
.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
})
希望有帮助。如有疑问,请在评论中提问。
关于angularjs - 从一个 Controller 访问另一个 Controller 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257798/