【发布时间】:2016-01-22 11:56:44
【问题描述】:
我是 Angularjs 的新手,学习了很多。但我坚持了一点。谷歌没有帮助我。我有一个控制器,我在 $scope.results 中有数据
app.controller('manage_categories', function($scope, $http, $filter, $window) {
$scope.results = [];
$http({
url: base_url + 'employee/fetchData?table=results',
method: "POST",
}).success(function(data) {
$scope.results = data;
});
})
现在我想在其他没有任何其他$http 呼叫的情况下访问相同的内容。我已经打完了另一个电话,但我不想要这个。因为我在许多其他控制器中需要这个。像这样的东西
app.controller('manage_users', function($scope, $http, $filter, $window,results) {
$scope.results = results;
//~ $http({
//~ url: base_url + 'employee/fetchData?table=results',
//~ method: "POST",
//~ }).success(function(data) {
//~ $scope.results = data;
//~ });
})
或任何其他方法。谢谢。
更新
我试过了
var myApp = angular.module('myApp',[]);
myApp.factory('results', function() {
return {
name : [{id:21,name:'this is test'}]
};
});
app.controller('manage_users', function($scope, $http, $filter, $window,results) {
$scope.results = results;
})
这工作正常。但不适用于 $http 调用。
var myApp = angular.module('myApp',[]);
myApp.factory('results', function($scope,$http) {
$scope.results=[];
$http({
url: base_url + 'employee/fetchData?table=results',
method: "POST",
}).success(function(data) {
$scope.results = data;
});
return {
name : results
};
});
更新 2
回答完后我会这样写
var canapp = angular.module('canApp', ["ngRoute", "angularFileUpload"]);
canapp.service('ResultsFactory', ['$http', function($http) {
// http call here
var url=base_url + 'employee/fetchData?table=results';
$http.post(url,data).success(function(data){
this.results = data;
});
}])
这样调用
canapp.controller('get_candidates', function($scope, $http, $filter, $timeout, $window, ResultsFactory) {
$scope.check=ResultsFactory.results;
});
但它没有在模板中设置值
【问题讨论】:
-
查看 $rootScope.broadcast,或者创建一个服务来共享数据
-
您需要服务或工厂来跨控制器共享数据。见Angular Service
-
在 manage_users 控制器上你必须使用 $promise try: results.name().then(function(data){$scope.results = data;});
-
您需要创建一个服务,在该服务中调用
$http,在对象$scope.results中收集数据,然后,您可以将服务注入任何控制器并访问@987654332 @ -
@PierreEmmanuelLallemant 你能解释一下我该怎么做吗?
标签: javascript angularjs