Nit*_*eli 1 http controllers angularjs
我试图在应用程序启动时加载JSON,并在我的所有控制器之间传播数据.我知道这不是很难做,但我对所有文章/答案感到困惑,因为他们使用的语法不同于我,有人可以指导我如何去做吗?
我目前正在使控制器生成$ http.get:
myApp = angular.module("myApp", [])
myApp.controller "HomeCtrl", ($scope, $http, $routeParams) ->
$http.get('gethome.php').success (data) ->
$scope.home = data
Run Code Online (Sandbox Code Playgroud)
但是我必须在每个想要访问该数据的控制器中重复自己
我将建议您使用Memoization模式和服务,并重用控制器中的服务
请检查以下示例代码
var app = angular.module('plunker', []);
app.service('cache', function ($http,$q) {
var mycache={};
return {
getdata: function (key) {
var deferred = $q.defer();
if (mycache[key]) {
deferred.resolve(mycache[key]);
}
else {
$http.get('TextFile.txt').then(function (data) {
mycache[key] = data.data;
deferred.resolve(mycache[key]);
});
}
return deferred.promise;
}
}
});
app.controller('test', function ($scope, cache) {
cache.getdata('cache').then(function (data) {
$scope.data = data;
});
});
app.controller('test1', function ($scope, cache) {
//since data is already cached now it will server the cached data
cache.getdata('cache').then(function (data) {
$scope.data = data;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
987 次 |
| 最近记录: |