web-dev-qa-db-ja.com

AngularJSの別のコントローラーから$ scope関数を使用する

あるコントローラーの$ scope関数を別のコントローラーで共有したいのですが、この場合はAngularUIダイアログです。

特に以下の例では、PopupCtrlで$ scope.scopeVarを使用できるようにしたいと考えています。

これは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

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

  <head>
    <script data-require="[email protected]" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script data-require="[email protected]" 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>

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>
12
ozandlb

次の2つの選択肢があります。

  1. 代わりに、rootScopeに接続されているコントローラー全体で使用できるスコーププロパティを設定できます。したがって、あなたの場合、それは次のようになります:
    $rootScope.scopeVar = "Data that will be available across controllers";ただし、これを使用することはお勧めしません-読み取り よくある落とし穴

  2. サービス 。再利用する機能やデータがある場合は、いつでもサービスを利用できます。

あなたのケースでは、データを保存し、変更を許可し、必要な人にデータを渡すサービスを作成できます。 これ 回答で詳しく説明しています。

31
callmekatootie