在AngularJS中使用另一个控制器中的$scope函数

29 浏览
0 Comments

在AngularJS中使用另一个控制器中的$scope函数

这个问题在这里已经有答案了

一个AngularJS控制器能否调用另一个控制器?

我想在另一个控制器中分享一个控制器的$scope函数,特别地,在这个例子中是为了一个AngularUI对话框。

具体来说,在下面的例子中,我想让$scope.scopeVar在PopupCtrl中可用。

这里有一个Plunkr

根据mlarcher的评论解决代码

main.js

angular.module('MyApp', ['ui.bootstrap']);
var MainCtrl = ['$scope', '$dialog', '$rootScope', function($scope, $dialog, $rootScope) {
  $scope.myTestVar = "hello";
  $scope.myOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: true,
    resolve: { MainCtrl: function() { return MainCtrl; }},
    templateUrl: 'myPopup.html',
    controller: 'PopupCtrl'
  };
  $scope.scopeVar = 'scope var string that should appear in both index.html and myPopup.html.';
  $rootScope.rootScopeVar = "rootScope var string that should appear in both index.html and myPopup.html.";
  $scope.openDialog = function() {
    var d = $dialog.dialog($scope.myOpts);
    d.open().then(function() {
      $scope.scopeVar = 'scope var string should be changed after closing the popup the first time.';
      $rootScope.rootScopeVar = 'rootScope var string should be changed after closing the popup the first time.';
    });
  };
}];
var PopupCtrl = ['$scope', 'dialog', 'MainCtrl', function ($scope, dialog, MainCtrl) {
   var key;
   for (key in MainCtrl) {
     $scope[key] = MainCtrl[key];
   }
   $scope.close = function(){
     dialog.close();
   }
 }];

index.html


  
    

{{scopeVar}}

 

{{rootScopeVar}}


myPopup.html

{{scopeVar}}

 

{{rootScopeVar}}

admin 更改状态以发布 2023年5月23日
0
0 Comments

你有两个选择:

  1. 你可以使用作用域(scope)属性,它应该在rootScope上附加并可在关联的控制器之间使用。所以在你的情况下,它将是:
    $rootScope.scopeVar = "可在控制器之间使用的数据"; 但是,不建议使用这种方式-请阅读常见陷阱

  2. 服务。每当你需要重复使用的功能或数据时,最好使用服务。

在你的情况下,你可以创建一个存储数据的服务,允许改变数据并将数据传递给需要它的人。 这个回答详细描述了它。

0