我卡住了,任何人都可以帮助我。这是代码。我正在编写 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
})
任何人都可以帮助解决这个问题。
答案 0 :(得分:3)
像这样写你的服务,
.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
})
希望它有所帮助。如有任何疑问,请在评论中提问。
答案 1 :(得分:-1)
你需要注射工厂:
q)([]sym:2 3 4 6 7 8; y: 100 200 300 400 500 600; x:90 0N 0N 90 0N 0N)
sym y x
----------
2 100 90
3 200
4 300
6 400 90
7 500
8 600
您的其他控制器也一样。