如何在没有持续服务器请求的情况下在 AngularJS 中进行视图重定向
How to make View redirects in AngularJS without constant server requests
每次
当我进行View
重定向时(我使用 href 这样做),我可以看到 AngularJS 运行GetAjaxData1
,GetAjaxData2
。换句话说:我每次进行重定向时都会这样做,而不是对服务器的单个初始请求View
请求。怎么了?
这是我的AngularJS代码:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
var factory = {};
data1 = [];
data2 = [];
factory.getAjaxData1 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data1 = result;
}
});
return data1;
};
factory.getAjaxData2 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data2 = result;
}
});
return data2;
}
};
var controllers = {};
controllers.uController = function ($scope, $location, uFactory) {
$scope.data1 = uFactory.getAjaxData1();
$scope.data2 = uFactory.getAjaxData2();
};
您绝对必须阅读有关$http和ng资源库的信息,并且 在您的应用程序中尝试更多角度的方式,您也应该 了解 AJAX 请求始终是异步的,并尝试 了解承诺模式。
从技术上讲 - 你需要的是缓存 - 无论你如何实现这一点 - 你都需要对 API 和 to cache 变量进行一次调用。
我不喜欢使用 $.ajax 的想法,但它看起来像这样:
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
return {
getFirstPromise: function () {
if (!this.$$firstPromise) {
this.$$firstPromise = $.ajax({
url: url,
type: 'GET',
contentType: "application/json"
}).then(function (data) {
window.data1 = data;
});
}
return this.$$firstPromise;
}
... //some other code
}
});
var controllers = {
uController: function ($scope, $location, uFactory) {
uFactory.getFirstPromise().then(function (data) {
$scope.data1 = data;
});
// same for other data - and don't try to make ajax requests synhronous ;-)
}
};
控制器不是单例。因此,每次您的视图更改时都会创建您的"UController"。我假设工厂是在这个控制器内部使用的。请参阅:AngularJS控制器的生命周期是什么?
相关文章:
- AngularJS绑定没有'在没有填充父范围的情况下无法工作
- 在禁用ng的情况下搜索JSON对象(AngularJS)
- AngularJs,在没有隔离的情况下将指令属性添加到作用域
- 在不引用文档的情况下使用AngularJS获取元素
- AngularJS可以在没有任何服务器端技术的情况下将文件保存/写入服务器
- AngularJS在不使用变量的情况下将服务注入模块中,这样就可以缩小它
- 如何在没有JQuery的情况下正确实现无限滚动的AngularJS表
- AngularJs/GitHub :如何在没有任何历史记录的情况下将角度种子克隆到我的新项目中
- Angularjs-在不更新当前控制器和模板的情况下更改URL
- 如何在没有任何浏览器插件的情况下调试AngularJS绑定{{expression}}
- AngularJs:默认情况下未选择单选按钮
- 想知道我是否可以在不了解高级JavaScript的情况下开始学习Angularjs
- 为什么不't AngularJS希望在值重复的情况下列出数组项
- 如何使 AngularJS 指令在不隔离作用域的情况下清楚地定义其依赖关系
- AngularJS:在没有$watch的情况下观察变量
- 数据绑定在特定情况下不起作用(AngularJS)
- AngularJS:在不修改ng模型的情况下获取选择标签
- 默认情况下,在 angularjs 中选择下拉列表中的最后一个位置显示占位符
- 如何在没有 AngularJs 编码的情况下在图像“alt”标签中使用字符串
- Angularjs in rails:在不重新加载的情况下更改页面