11
我想在另一個控制器中共享一個控制器的$ scope函數,在這種情況下用於AngularUI對話框。
特別是在下面的例子中,我想$ scope.scopeVar在PopupCtrl中可用。
Resolve code based on mlarcher's comment here
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="[email protected]*" 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>
反之,不創建其唯一目的在生活中是存儲和返回數據的位數,當然服務,全局狀態和吮吸您應該謹慎使用$ rootScope,就像你(希望)與全局變量使用任何語言。特別是,不要將它用於代碼,只用於數據。如果您試圖在$ rootScope上放置一個函數,那麼將它放入一個可以在需要的地方注入的服務會更好,並且更容易進行測試.article說[$ rootScope存在,但它可以用於惡魔] https://docs.angularjs.org/partials/misc/faq.html#drootscopeexistsbutitcanit canbeforeforevil – Buddhi
我認爲還有第三種選擇:在第三個控制器的範圍內包含兩個控制器,然後使用每個內部的$ parent共享數據兒童控制器。 – ftexperts