使用AngularJS中不同控制器的$ scope函数

oza*_*dlb 12 javascript angularjs angular-ui angular-ui-bootstrap

我想在另一个控制器中共享一个控制器的$ scope函数,在本例中是一个AngularUI对话框.

特别是在下面的例子中,我希望$ scope.scopeVar在PopupCtrl中可用.

这是一个普兰克

在此处根据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();
   }
 }];
Run Code Online (Sandbox Code Playgroud)

的index.html

<!DOCTYPE html>
<html ng-app="MyApp">

  <head>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script data-require="ui-bootstrap@0.3.0" data-semver="0.3.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.3.0.min.js"></script>
    <script src="script.js"></script>
    <link data-require="bootstrap-css@*" data-semver="2.3.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
    <link rel="stylesheet" href="style.css" />
  </head>

  <body ng-controller="MainCtrl">
    <h4>{{scopeVar}}</h4>
    <h4>{{rootScopeVar}}</h4>
    <br>
    <button class="btn btn-primary" type="button" data-ng-click="openDialog()" >Popup</button>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

myPopup.html

<div class="modal-body">
   <h4>{{scopeVar}}</h4>
   <h4>{{rootScopeVar}}</h4>
</div>
<div class="modal-footer">
   <button data-ng-click="close()" class="btn btn-large popupLarge" >Close</button>
</div>
Run Code Online (Sandbox Code Playgroud)

cal*_*tie 31

你有两个选择:

  1. 您可以拥有应该在连接到控制器的控制器之间可用的scope属性rootScope.所以在你的情况下,它看起来像:
    $rootScope.scopeVar = "Data that will be available across controllers";但是,建议不要使用它 - 阅读常见的陷阱

  2. 服务.只要您拥有要重复使用的功能或数据,您最好使用服务.

在您的情况下,您可以创建一个存储数据的服务,允许对其进行更改并将数据传递给任何需要它的人.这个答案详细描述了它.

  • 我认为还有第三种选择:在第三个控制器范围内包含两个控制器,然后使用每个子控制器内的$ parent共享数据. (4认同)