通过AngularJS中的服务在控制器之间传递数据不起作用

通过AngularJS中的服务在控制器之间传递数据不起作用,angularjs,service,controller,persistence,Angularjs,Service,Controller,Persistence,我有两个这样的控制器: myApp.controller('Ctrl1', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){ DataService.set('HelloWorld', 'TheValue') alert(DataService.value.TheValue + 'in Ctrl1'); }]); myApp.controll

我有两个这样的控制器:

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中,警报显示该值的值正确为HelloWorld。但当我导航到Ctrl2时,该值变为null

如何使DataService中的TheValue值在控制器之间持久化

编辑:

以下是我如何在控制器之间导航:

我的应用程序是一个Asp.NETMVC应用程序。Ctrl1是仪表板页面的AngularJS控制器,而Ctrl2是下一页的控制器,通过单击按钮和路由到新的Asp.Net控制器

仪表板页面代码段:

<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>

那么,下一页就是这样:

<body>
    <div ng-controller="Ctrl2"  class="ng-cloak">
          @*Page stuffz here...*@
    </div>
</body>

@*在这里翻页*@

它与以下代码一起工作。确保已设置控制器

演示
var myApp=angular.module('testApp',[]);
myApp.controller('Ctrl1',['$scope','DataService',function($scope,DataService){
$scope.setData=函数(){
DataService.set('HelloWorld','TheValue')
警报(DataService.value.TheValue+'在Ctrl1'中);
};
}]);
myApp.controller('Ctrl2',['$scope','DataService',function($scope,DataService){
$scope.getData=function(){
警报(DataService.value.TheValue+'在Ctrl2'中);
};
}]);
myApp.service(“数据服务”,函数(){
风险值数据={
值:null
};
函数集(值、字段){
数据[字段]=值;
}
返回{
集:集,,
值:数据
};
});

设置
得到

我的控制器位于不同的主体标签中是否重要?单独的.cshtml文件?不,这不重要。您可能并没有设置控制器“设置控制器”意味着什么,它和在声明函数之外设置和获取值有什么不同,就像我现在做的一样?我看不出你的代码和我的代码有什么明显的不同。你能强调一下我没有做正确的事情吗?检查控制台中是否有问题。控制台中没有问题。你能分享实际的代码吗?你说的“导航到Ctrl2”是什么意思?我添加了html。我希望这有帮助。