在 AngularJS 中观看模型更改时如何忽略初始负载? [英] How do I ignore the initial load when watching model changes in AngularJS?

查看:26
本文介绍了在 AngularJS 中观看模型更改时如何忽略初始负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页作为单个实体的编辑器,它作为 $scope.fieldcontainer 属性中的深层图形.从我的 REST API(通过 $resource)得到响应后,我向fieldcontainer"添加了一个手表.我正在使用此手表来检测页面/实体是否脏".现在我正在让保存按钮弹跳,但我真的想让保存按钮不可见,直到用户弄脏模型.

I have a web page that serves as the editor for a single entity, which sits as a deep graph in the $scope.fieldcontainer property. After I get a response from my REST API (via $resource), I add a watch to 'fieldcontainer'. I am using this watch to detect if the page/entity is "dirty". Right now I'm making the save button bounce but really I want to make the save button invisible until the user dirties the model.

我得到的是手表的单个触发器,我认为这是因为 .fieldcontainer = ... 分配在我创建手表后立即发生.我想只使用dirtyCount"属性来吸收最初的误报,但这感觉很hacky……我认为必须有一种Angular 惯用"方法来处理这个问题——我不是唯一一个使用手表检测脏模型.

What I am getting is a single trigger of the watch, which I think is happening because the .fieldcontainer = ... assignment takes place immediately after I create my watch. I was thinking of just using a "dirtyCount" property to absorb the initial false alarm but that feels very hacky ... and I figured there has to be an "Angular idiomatic" way to deal with this - I'm not the only one using a watch to detect a dirty model.

这是我设置手表的代码:

Here's the code where I set my watch:

 $scope.fieldcontainer = Message.get({id: $scope.entityId },
            function(message,headers) {
                $scope.$watch('fieldcontainer',
                    function() {
                        console.log("model is dirty.");
                        if ($scope.visibility.saveButton) {
                            $('#saveMessageButtonRow').effect("bounce", { times:5, direction: 'right' }, 300);
                        }
                    }, true);
            });

我一直认为必须有一种更简洁的方法来做到这一点,而不是用if (dirtyCount > 0)"来保护我的UI脏"代码......

I just keep thinking there's got to be a cleaner way to do this than guarding my "UI dirtying" code with an "if (dirtyCount >0)"...

推荐答案

在初始加载前设置一个标志,

set a flag just before the initial load,

var initializing = true

然后当第一个 $watch 触发时,执行

and then when the first $watch fires, do

$scope.$watch('fieldcontainer', function() {
  if (initializing) {
    $timeout(function() { initializing = false; });
  } else {
    // do whatever you were going to do
  }
});

标记将在当前摘要周期结束时拆除,因此不会阻止下一次更改.

The flag will be tear down just at the end of the current digest cycle, so next change won't be blocked.

这篇关于在 AngularJS 中观看模型更改时如何忽略初始负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆