控制器之间的数据共享不能按预期工作
Sharing data among controllers not working as expected
我试图在2个不同页面上的2个控制器之间共享数据,但它不像预期的那样工作
page1.html:
<form ng-controller="FormController">
<input ng-model="user.email">
</form>
page1controller.js:
app.controller("FormController", ['$scope', '$http', '$window', 'UserEmailService', function($scope, $http, $window, UserEmailService) {
// Code logic here
console.log($scope.user.email) // Code outputs a string here
UserEmailService.setEmail($scope.user.email);
$window.location.href = "/page2"; // Redirects to page2.html after logic completes
}]);
page2.html:
<div controller="SomeController">
<p> Hi, your e-mail is {{ email }} </p>
</div>
SomeController.js:
app.controller("SomeController", ['$scope', 'UserEmailService', function($scope, UserEmailService) {
console.log(UserEmailService.getEmail()); // outputs undefined
$scope.email = UserEmailService.getEmail();
}]);
UserEmailService.js
app.service("UserEmailService", function(){
var email = [];
var setEmail = function(val) {
email.push(val);
};
var getEmail = function() {
return email.pop();
};
return {
setEmail : setEmail,
getEmail : getEmail
};
});
我试图从page1.html中获取用户电子邮件并在page2.html上显示它,但它总是在page2.html上显示为未定义。我做错了什么?
在FormController
中,$window.location.href
将导致整个页面重新加载,从而使您的服务状态重置。尝试$location.url('')
导航到该路线。它不会导致整个页面重新加载。
如果您希望您的数据在整个页面重新加载后可用。你应该使用localstorage之类的东西。
使用factory代替service。更多信息angular。Service vs . angular.factory
app.factory("UserEmailService", function(){
var email = [];
var setEmail = function(val) {
email.push(val);
};
var getEmail = function() {
return email.pop();
};
return {
setEmail : setEmail,
getEmail : getEmail
};
});
在您的监听控制器(SomeController)
$scope.$watch(function () {
return UserEmailService.getEmail();
},
function (newValue, oldValue) {
if (newValue !== oldValue){
$scope.user.email = newValue;
}
});
最后的代码看起来像
app.controller("SomeController", ['$scope', 'UserEmailService', function($scope, UserEmailService) {
$scope.$watch(function () { return UserEmailService.getEmail();},
function (newValue, oldValue) {
if (newValue !== oldValue){
$scope.user.email = newValue;
}
});
}]);
相关文章:
- jQuery dosn'内联函数不能按预期工作
- Javascript-将函数分配给变量dos'不能按预期工作
- JavaScript - 为什么加法赋值运算符不能按预期工作
- Node.js承诺q不能按预期工作
- 为什么 javascript 中的 for 循环不能按预期工作
- 为什么.on()在jquery中不能按预期工作
- Undercore模板没有'不能按预期工作
- javascript命令可以单独工作,但不能按顺序作为bookmarklet
- 为什么这个简单的 for 循环不能按预期工作
- 为什么我的Javascript函数不能按预期工作
- 为什么.size()不能按我认为的方式工作
- 否定字符不能按预期工作?^
- 为什么我的addClass removeClass和事件处理程序不能按预期工作
- .getElementById(“;)不能按要求工作
- three.js lookat()函数不能按我的需要工作
- 排序dgrid列不能按预期工作
- 控制器之间的数据共享不能按预期工作
- 创建由每个子数组的最大值组成的数组不能按预期工作
- 要求定义的模块不能按预期工作
- 以编程方式调用onclick和onchange不能按预期工作