简体   繁体   English

为什么跨控制器共享数据在AngularJS中不起作用

[英]Why sharing data across controllers doesn't work in AngularJS

I am trying to build a simple username login system. 我正在尝试构建一个简单的用户名登录系统。 This is just to record username which I can use in my various controllers. 这只是为了记录我可以在各种控制器中使用的用户名。

But, for some reason, I am unable to get $scope.userName value in abcController 但是,由于某种原因,我无法在abcController获取$scope.userName

The essence of this problem is sharing data across controllers. 这个问题的实质是跨控制器共享数据。

controller.js 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 resource.js

app.factory('Session', function() {
    var Session = {
        data: {},
        updateSession: function(userName) {
            Session.data = { "username": userName }
        }
    };
    return Session;
});

As soon as a user clicks on LogIn button a twitter-bootstrap modal(popup) will appear and ask user to enter their username. 一旦用户点击LogIn按钮,就会出现twitter-bootstrap模式(弹出窗口)并要求用户输入他们的用户名。

index.html 的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>

Please feel free to suggest, if there is better way to do what I am trying to do above. 请随时提出建议,如果有更好的方法来做我上面尝试做的事情。

Does it help if you define your resource like this? 如果您定义这样的资源会有帮助吗?

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;
});

I think what may be happening (and I can't see all of your code) but I don't think username is set when you take a reference in abcController . 我认为可能会发生什么(我看不到你的所有代码)但我不认为在abcController引用时会设置username By defining a shared reference in your object schema first that abcController can attach to, it will reflect the changes later when updateSession() is called. 通过首先在对象模式中定义一个abcController可以附加的共享引用,它将在以后调用updateSession()时反映更改。

Here's a working example using your service idea. 这是一个使用您的服务理念的工作示例

I found an alternate solution using emit and broadcast . 我找到了使用emitbroadcast的替代解决方案。 Full code example in this jsfiddle 这个jsfiddle中的完整代码示例

app.js 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 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM