【问题标题】:Message in Popup can't be delivered because of changed scope by $location.path由于 $location.path 更改了范围,因此无法传递 Popup 中的消息
【发布时间】:2015-04-14 03:09:50
【问题描述】:

如果用户按下保存按钮,会发生如下逻辑:

Popup.notifyPopup($scope, "Saved...")
$location.path('/changeView');

Popup.notifyfyPopup 函数是将第二个参数中的消息设置到作用域中并在通知弹出窗口中通知消息的函数。

function notifyTopNotification(scope, msg) {

        sharedProperties.setNotifyMsg(msg);

        ngDialog.open({

             template: 'notifyTopNotification',
             controller: function() {4
                 $scope.notifyMsg = sharedProperties.getNotifyMsg();
             },
             className: 'ngdialog-close',
             scope: $scope
         });

         setTimeout(1000);
 };  

notifyPopup : function(scope, msg) {

        $scope = scope;
        notifyTopNotification($scope, msg);
    }

大多数情况下,它有效。但是 location.path() 后面的函数不起作用。因为 location.path() 函数改变了范围。我该怎么做?

【问题讨论】:

    标签: angularjs angularjs-scope


    【解决方案1】:

    如果您尝试在作用域之间传递消息,您可能希望使用 $broadcast 发送消息并使用 $on 侦听广播。但请注意,您必须已经实例化接收控制器,否则它将无法工作。在这种情况下,您将首先启动状态更改(这将实例化接收控制器),然后 $broadcast 消息。

    如果作用域之间存在父/子关系,则以下工作:

    function firstCtrl($scope){
    $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope){
    $scope.$on('someEvent', function(event, mass) {console.log(mass)});
    }
    

    但如果没有,则需要使用$rootScope:

    function firstCtrl($rootScope){
    $rootScope.$broadcast('someEvent', [1,2,3]);
    }
    

    Broadcast 将消息从父范围触发到子范围。如果你需要向上游发送消息,你可以做同样的事情,但你需要使用 $emit 而不是 $broadcast。

    文档中还提供了更多信息: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多