Angularjs 无法访问同一控制器中的$scope变量

Angularjs 无法访问同一控制器中的$scope变量,angularjs,Angularjs,因此,我在视图1中有一个表单提交按钮——main.html <div ng-init="init()" ng-controller="ReadController"> <button type="submit" class="btn btn-primary" ng-click="getFile()">Show File</button> </div> 这是我的路由配置 mainApp.config(function($routeP

因此,我在视图1中有一个表单提交按钮——main.html

<div ng-init="init()" ng-controller="ReadController">
    <button type="submit" class="btn btn-primary" ng-click="getFile()">Show File</button>
</div>
这是我的路由配置

    mainApp.config(function($routeProvider) {
        $routeProvider.when('/showFile',{
            controller:'ReadController',templateUrl:'viewFile.html'});
});
这是我的视图2——viewFile.html

<div ng-controller="ReadController" class="container">
{{fileContent}}
</div>

{{fileContent}}

我得到的输出是“hi”,而不是“new hi”。导航到同一控制器内的不同页面时,$scope是否重置?

问题是,您不应该使用
ngController
指令重新声明控制器,因为您已经通过路由配置声明了它

这是
main.html
viewFile.html
文件的正确内容:

<div ng-init="init()">
    <button type="submit" class="btn btn-primary" ng-click="getFile()">Show File</button>
</div>

<div class="container">
    {{fileContent}}
</div>

Vinod-$scope是唯一一个非单例对象(注入控制器中)。注入angularjs控制器/指令/服务的任何其他对象都是单例对象。您可能需要重写控制器以接受服务,并且可以将服务变量更改为“new Hi”。如果在第二个视图中使用此选项,您将看到更改。有关更改的代码,请参见下文

sampleController = app.controller(ReadController,["ReadService","$Scope", function(readService,$scope){

readService.fileContent = "Hi";
$scope.getFile = function() {
        console.log("Chosen file:" + $scope.fileName);
        $location.path("/showFile");
        readService.fileContent = "new hi";
}]);

不是唯一的。控制器本身也不是单例。因此,它在转到第二个视图时重新实例化,并重新实例化它,重新执行行
$scope.fileContent=“Hi”。因此,即使作用域是单例(我同意它不是单例),OP的代码也不会工作。这就是我使用服务变量的原因。服务是单例的,建议的代码可以使用。你能看看这个插件吗。我试着用一个服务来实现它:Vinoth-是的,这就是我的意思。保存在服务中的值将是可通过应用程序访问的值。它不会被初始化。Sry Subash,但我认为您提供的plunkr在单击按钮Show file时没有任何作用。如果我遗漏了什么或提供了一个工作plnkr,你能帮我吗?我如何使用一个控制器来实现这一点?在我看来,ReadController似乎是多余的。请帮助我理解。然后你要么使用rootScope,要么像在另一个答案中那样使用服务。我不知道您正在构建什么,但拥有另一个控制器用于单独的路由实际上是一个明智的选择,并且在代码演化后不会冗余。但如果它是冗余的,那么就使用服务。我已经尝试过用一个控制器修改您的plunk&包括一个服务。还是不能用
sampleController = app.controller(ReadController,["ReadService","$Scope", function(readService,$scope){

readService.fileContent = "Hi";
$scope.getFile = function() {
        console.log("Chosen file:" + $scope.fileName);
        $location.path("/showFile");
        readService.fileContent = "new hi";
}]);