【问题标题】:AngularJS - $watch not triggered even though value changedAngularJS - 即使值更改,$watch 也不会触发
【发布时间】:2013-03-29 18:02:11
【问题描述】:

我正在使用 AngularJS 和 twitter 引导程序。

我有一个表,这个表属于父控制器。
我有一个弹出窗口,它属于子控制器。

当用户单击表格中的一行时,会显示弹出窗口,其中包含有关所选行的更多信息。

这是我当前代码的样子:

function ParentCtrl($scope) {
    //called when a row is clicked
    $scope.showMoreInfo = function() {
        $scope.showModal = true;
    }
}

function ChildCtrl($scope) {
    $scope.$watch('showModal', function() {
        if($scope.$parent.showModal !== true) {
            return;
        }

        //Show the popup - #myModal is the ID of the popup div 
        jQuery("#myModal").modal("show");
    });

    //When the popup is closed, change the value
    jQuery("#myModal).on("hide", function() {
        $scope.$parent.showModal = false;
    });
}

现在,这种机制完美运行 - 当用户单击该行时,将显示包含该行详细信息的弹出窗口(我使用此处未包含的服务将详细信息从 ParentCtrl 传输到 ChildCtrl 以关注手头的问题)。
当用户单击弹出窗口中的“X”或关闭按钮时,模式会按预期关闭。进一步单击该行也可以顺利进行,并且弹出窗口按预期显示。

我的问题在于通过单击弹出窗口之外的区域关闭弹出窗口。基本上,如果您使用过引导模式 (http://twitter.github.io/bootstrap/javascript.html#modals),您就会知道弹出窗口之外有一个区域在背景中隐约显示网页,并且可以通过单击窗口之外的区域来关闭弹出窗口弹出窗口 - 这不是通过弹出窗口中的“X”或关闭按钮,而是通过简单地单击弹出容器外部。

虽然调用jQuery("#myModal").on('hide', function() {..});$scope.$parent.showModal 的值设置为false,但永远不会触发$scope.$watch(..)
当用户以这种方式关闭弹出窗口后点击另一行时,虽然$scope.showModal设置为true,但$scope.$watch(..)再次不会被触发。

知道当用户以异常方式关闭弹出窗口时出了什么问题,这里有什么解决方案?

【问题讨论】:

  • 你见过docs.angularjs.org/misc/faq 吗?尤其是 Common Pitfall -> Dom Manipulation 部分?
  • 谢谢指出;虽然我需要在 AngularJS 上做更多的工作来理解为什么我必须将 DOM 操作移动到指令中......

标签: twitter-bootstrap angularjs


【解决方案1】:

每当一个范围属性在 Angular 监督之外发生变化时(例如 DOM 事件),您都需要引发一个 $digest 循环。

为此,请在更改属性后添加一个 $scope.$apply()。

//When the popup is closed, change the value
jQuery("#myModal).on("hide", function() {
    $scope.$parent.showModal = false;
    $scope.$apply();
});

无论如何,正如@ganaraj 所说,请阅读Common Pitfall -> Dom Manipulation section。您必须所有 dom 操作包含在一个指令中,绝不在控制器中。

【讨论】:

  • 我将代码转移到指令内部,即使这样,问题也发生了。我不得不使用$scope.$apply() 让它在指令中也能工作(我当时在想别的)。无论如何,显然,正确的方法是 `$scope.$apply(function() {$scope.$parent.showModal = false}); - 与异常有关。它在 24 分钟左右解释了 here...
猜你喜欢
  • 2016-03-10
  • 1970-01-01
  • 2014-04-08
  • 2013-03-08
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
相关资源
最近更新 更多