Angularjs 如何在angular js中声明控制器外部的变量
我想声明一个我想在两个控制器中使用的变量。一个控制器用于发布值,第二个控制器用于从数据库获取值。我使用了一个工厂,它返回时间戳 这是我的代码:Angularjs 如何在angular js中声明控制器外部的变量,angularjs,Angularjs,我想声明一个我想在两个控制器中使用的变量。一个控制器用于发布值,第二个控制器用于从数据库获取值。我使用了一个工厂,它返回时间戳 这是我的代码: mainApp.factory('methodFactory', function () { return { myMethod: function () { var date = new Date(); //console.log(date); var unique = ((date.getMonth()+1)
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
()时,值已更改。有没有办法使两个控制器中的值相同。这是正常的,因为myMethod()
函数总是返回一个新的日期()。您不会将信息存储在当前对象中
将计算出的唯一变量存储在服务中,并为此服务中的值提供getter和setter
下面是一个简单的示例,其中有两个控制器,第一个控制器设置服务中的值,第二个控制器从服务中获取值:
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>
安古拉斯普朗克
文件。写(“”);
提交
{{getDate()}}
- 使用$rootScope声明或在服务中声明
这些值是否仅相隔几秒钟?您能否展示一下您是如何使用工厂的?