【问题标题】:sharing data between controllers of different html pages using rootscope使用 rootscope 在不同 html 页面的控制器之间共享数据
【发布时间】:2016-09-07 14:46:28
【问题描述】:
<td colspan="1">{{case.Name}}</td>
<td colspan="1">{{case.total}}</td>
<td colspan="1">{{case.passed}}</td>
<td colspan="1">{{case.failed}}</td>
<td colspan="1" ng-click="showAll(case.Name)">{{case.totalCheck}}</td>

当用户单击此列 (totalCheck) 时,名称存储在变量 $rootscope.name 中,并在我需要此变量的位置打开另一个 html 页面。 这个控制器被命名为 angular1。

analyzer.run(function($rootScope) {
    $rootScope.name= '';
}); 

$scope.showAll=function(item){
    $rootScope.name= item;  
    $window.open('/scripts.html');
}

对于另一个页面,我有另一个控制器

var analyzer = angular.module('analyzer', []);

analyzer.controller('angular2', function($scope, $rootScope) {
    alert($rootScope.name);
});

这里说name的值是未定义的。你如何在两页之间共享变量? .

【问题讨论】:

  • 你的两个控制器都属于同一个模块吗??
  • 是的。但是当另一个 html 打开时,它会再次重新加载角度文件并创建新的范围。所以也许这个值会被重置
  • 如果您可以使用服务或工厂来代替 $rootScope
  • 不会发生同样的事情吗?在新页面中,它将加载角度文件并创建新范围。所以服务中的初始值将为变量设置?
  • 你想在哪里显示那个 html 页面?

标签: angularjs rootscope


【解决方案1】:

我认为你应该在这里使用 ngRoute。

按照以下步骤操作(您甚至可以使用hrf="#/scripts.html/{{case.Name}}" 并且可以将case.name 传递为routeParams 而无需使用$rootScope):

1) 包括 //ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js 2) 如下更改您的功能。

analyzer.run(function($rootScope,$location) {
        $rootScope.name= '';
    }); 

  $scope.showAll=function(item){
        $rootScope.name= item;

      $location.path('/scripts.html');
  }

3) 为您的路由添加配置。

var analyzer = angular.module('analyzer', ['ngRoute']);
analyzer.config(function($routeProvider) {
    $routeProvider
    .when("/scripts.html", {
        templateUrl : "scripts.html"
    });
});

【讨论】:

  • 我会试试这个,但 $location.path 会在同一个选项卡中打开它。如果我使用相同的位置但不在新标签中,路由可能会起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多