[英]Why sharing data across controllers doesn't work in AngularJS
我正在嘗試構建一個簡單的用戶名登錄系統。 這只是為了記錄我可以在各種控制器中使用的用戶名。
但是,由於某種原因,我無法在abcController
獲取$scope.userName
值
這個問題的實質是跨控制器共享數據。
controller.js
app.controller('userNameController',function ($scope, $log, Config, Session)
{
Session.updateSession($scope.userName);
});
app.controller('abcController',function ($scope, $log, Config, Session)
{
$scope.userName=Session.data.username;
//some other code
});
resource.js
app.factory('Session', function() {
var Session = {
data: {},
updateSession: function(userName) {
Session.data = { "username": userName }
}
};
return Session;
});
一旦用戶點擊LogIn按鈕,就會出現twitter-bootstrap模式(彈出窗口)並要求用戶輸入他們的用戶名。
的index.html
<div ng-controller="userNameController">
<button class="btn" id="enterUsernameBtn" href="#userNameModal" role="button" class="btn" data-toggle="modal" title="Enter Username">Login</button>
</div>
<!-- UserName Modal -->
<div id="userNameModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="userNameModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="userNameModalLabel">Enter your username</h3>
</div>
<div class="modal-body">
<p><b>UserId</b></p>
<div class="input-append">
<input class="pull-left" id="userIdTextBox" type="text" style="left:8px; width:160px" ng-controller="userNameController" ng-model="userName">
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Submit</button>
</div>
</div>
請隨時提出建議,如果有更好的方法來做我上面嘗試做的事情。
如果您定義這樣的資源會有幫助嗎?
app.factory('Session', function() {
var Session = {
data: { username: undefined }, // ensure object ref to attach to
updateSession: function(userName) {
Session.data.username = userName; // do NOT recreate the object above
}
};
return Session;
});
我認為可能會發生什么(我看不到你的所有代碼)但我不認為在abcController
引用時會設置username
。 通過首先在對象模式中定義一個abcController可以附加的共享引用,它將在以后調用updateSession()時反映更改。
這是一個使用您的服務理念的工作示例 。
我找到了使用emit
和broadcast
的替代解決方案。 這個jsfiddle中的完整代碼示例
app.js
app.run(function($rootScope) {
/*
Receive emitted message and broadcast it.
Event names must be distinct or browser will blow up!
*/
$rootScope.$on('handleEmit', function(event, args) {
$rootScope.$broadcast('handleBroadcast', args);
});
});
controller.js
app.controller('userNameController',function ($scope, $log, Config)
{
$scope.submitUserName= function ()
{
// Session.updateSession($scope.userName);
$scope.$emit('handleEmit', {username: $scope.userName});
};
});
app.controller('abcController',function ($scope, $log, Config)
{
$scope.$on('handleBroadcast', function(event, args) {
$scope.userName = args.username;
});
//some other code
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.