gpt4 book ai didi

angularjs - 无法访问同一 Controller 内的 $scope 变量

转载 作者:行者123 更新时间:2023-12-02 23:38:21 24 4
gpt4 key购买 nike

所以我的 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变量

$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'});
});

这是我的 View 2 -- viewFile.html

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

我得到的输出是“hi”而不是“new hi”。当导航到同一 Controller 中的不同页面时,$scope 是否会重置?

最佳答案

Vinod - $scope 是唯一一个不是单例的对象(被注入(inject)到 Controller 中)。注入(inject)到 AngularJS Controller /指令/服务中的任何其他对象都是单例的。您可能必须重写 Controller 才能接受服务,并且可以将服务变量更改为“new Hi”。如果您在第二个 View 中使用它,您将看到更改。请参阅下面的更改后的代码。

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

关于angularjs - 无法访问同一 Controller 内的 $scope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com