无法在同一控制器中访问$ scope变量 [英] Unable to access $scope variable within same controller

查看:51
本文介绍了无法在同一控制器中访问$ scope变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have this form submit button in my view 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变量

Here is my js for modifying the fileContent variable in getFile()

$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

Here is my view 2 -- viewFile.html

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

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

I get the output as "hi" and not "new hi". Does the $scope get reset when navigating to a different page within the same controller?

推荐答案

Vinod-$ scope是唯一不是单例的对象(注入到控制器中).注入到angularjs控制器/指令/服务中的任何其他对象都是单例.您可能必须重写控制器才能接受服务,并且可以将服务变量更改为"new Hi".如果在第二个视图中使用此选项,则将看到更改.参见下面的更改代码.

Vinod - $scope is the only object (which is injected into the controller) that's not singleton. Any other object which is injected into angularjs controllers/directives/services are singleton. You might have to rewrite your controller to accept a service and you can change the service variable to "new Hi". If you use this in the second view, you'll see the changes. See below for the changed code.

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变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆