我想声明一个我想在两个控制器中使用的变量。一个控制器用于发布值,第二个控制器用于从db获取值。我使用了工厂并返回时间戳。
这是我的代码:
mainApp.factory('methodFactory', function () {
return { myMethod: function () {
var date = new Date();
//console.log(date);
var unique = ((date.getMonth()+1) + '' + date.getDate() + '' + date.getFullYear() + ''+ date.getHours() +''+ date.getMinutes() +''+ date.getSeconds());
return unique;
//console.log("methodFactory - myMethod");
}
}
});
当我在控制器中使用methodFactory
()时,值已更改。有没有办法在两个控制器中都有相同的值。
答案 0 :(得分:0)
这是正常的,因为myMethod()
函数总是返回一个新的Date()。您不会将信息存储在当前对象中。
将计算出的唯一变量存储在服务中,并为此服务中的值提供getter和setter。
这是一个带有两个控制器的简单示例,其中第一个控制器设置服务中的值,第二个控制器从服务获取值: http://plnkr.co/edit/4WRtfVF3DnOfPDXz9mq0?p=preview
<强> JS 强>
var app = angular.module('plunker', []);
app.controller('MainCtrl', MainCtrl);
app.controller('SecondCtrl', SecondCtrl);
function MainCtrl($scope, sharedDataService) {
$scope.setDate= function(){
var date = new Date();
var unique = ((date.getMonth()+1) + '' + date.getDate() + '' + date.getFullYear() + ''+ date.getHours() +''+ date.getMinutes() +''+ date.getSeconds());
sharedDataService.setDate(unique);
}
}
function SecondCtrl($scope, sharedDataService) {
$scope.getDate=function(){
return sharedDataService.getDate();
}
}
app.service('sharedDataService', function() {
var uniqueDate;
this.getDate = function() {
return uniqueDate;
}
this.setDate= function(newDate) {
uniqueDate=newDate;
}
});
<强> HTML 强>
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<button ng-click="setDate()">submit</button>
</div>
<div ng-controller="SecondCtrl">
<div>{{getDate()}}</div>
</div>
</body>
</html>
答案 1 :(得分:0)