我有两个控制器,如:
myApp.controller('Ctrl1', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
DataService.set('HelloWorld', 'TheValue')
alert(DataService.value.TheValue + 'in Ctrl1');
}]);
myApp.controller('Ctrl2', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
alert(DataService.value.TheValue + ' in Ctrl2');
}]);
我的服务定义如下:
myApp.service("DataService", function () {
var data = {
TheValue: null
};
function set(value, field) {
data[field] = value;
}
return {
set: set,
value: data
};
});
在Ctrl1中,警报显示TheValue的值是正确的HelloWorld。但是当我导航到Ctrl2时,TheValue变为空。
如何让DataService中的TheValue值在控制器之间保持?
修改
以下是我在控制器之间导航的方法:
我的应用程序是Asp.Net MVC应用程序。 Ctrl1是Dashboard页面的AngularJS控制器,而Ctrl2是下一页的控制器,通过单击按钮并路由到新的Asp.Net控制器。
Dashboard Page snippet:
<body>
<div class="row" ng-controller="Ctrl1">
<div class="col-sm-4">
<ul class="dashboard-list">
<li>
<div class="tile">
<a href="/NextPage" title="The Next Page">
<h2>Schedule New Visit</h2>
</a>
</div>
</li>
</ul>
</div>
</body>
然后,NextPage就像这样:
<body>
<div ng-controller="Ctrl2" class="ng-cloak">
@*Page stuffz here...*@
</div>
</body>
答案 0 :(得分:1)
使用以下代码进行操作。确保已设置控制器。
<强>样本强>
var myApp = angular.module('testApp',[]);
myApp.controller('Ctrl1', ['$scope', 'DataService', function ($scope, DataService){
$scope.setData = function(){
DataService.set('HelloWorld', 'TheValue')
alert(DataService.value.TheValue + 'in Ctrl1');
};
}]);
myApp.controller('Ctrl2', ['$scope', 'DataService', function ($scope, DataService){
$scope.getData = function(){
alert(DataService.value.TheValue + ' in Ctrl2');
};
}]);
myApp.service("DataService", function () {
var data = {
TheValue: null
};
function set(value, field) {
data[field] = value;
}
return {
set: set,
value: data
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" >
<div ng-controller="Ctrl1">
<button ng-click="setData()">SET
</button>
</div>
<div ng-controller="Ctrl2">
<button ng-click="getData()"> GET
</button>
</div>
</body>