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

时间:2015-09-18 05:36:56

标签: 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>

这是我在js中修改getFile()

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

这是我的路由配置

    mainApp.config(function($routeProvider) {
        $routeProvider.when('/showFile',{
            controller:'ReadController',templateUrl:'viewFile.html'});
});

以下是我的观点2 - viewFile.html

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

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

2 个答案:

答案 0 :(得分:2)

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";
}]);

答案 1 :(得分:0)

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

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

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

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

当然要确保将ngView放在将加载两个部分的页面上。

然后,您可能会有一些主控制器,您可以在其中定义业务逻辑($scope.getFile方法)。看看下面的演示。

angular.module('demo', ['ngRoute'])

.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'ReadController',
        template: '<div ng-init="init()"><button type="submit" class="btn btn-primary" ng-click="getFile()">Show File</button></div>'
    })
    .when('/showFile', {
        controller: 'ReadController',
        template: '<div class="container">{{fileContent}}</div>'
    });
})

.controller('MainCtrl', function($scope, $location) {
    $scope.fileContent = "Hi";
    $scope.getFile = function() {
        $location.path("/showFile");
        $scope.fileContent = "new hi";
    };
})

.controller('ReadController', function() {
    // some stuff here
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-route.min.js"></script>

<div ng-app="demo" ng-controller="MainCtrl">
    <ng-view></ng-view>    
</div>

演示: http://plnkr.co/edit/zyuFaovCU5ZEVJMNRRJL?p=preview

以上作品是因为ReadControllerMainController的孩子,通过原型链继承了父作用域,它自然也可以访问fileContent