如何看着AngularJS模式的变化,当我忽略了初始负荷? [英] How do I ignore the initial load when watching model changes in AngularJS?

查看:131
本文介绍了如何看着AngularJS模式的变化,当我忽略了初始负荷?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,作为编辑为一个单一的实体,它位于如$ scope.fieldcontainer财产深刻的图表。之后,我从我的REST API(通过$资源)的响应,我的手表添加到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属性来吸收初始误报但感觉非常哈克......我想通必须有一个角地道的方式来处理这个 - 我不是唯一的一个用手表来检测一个肮脏的典范。

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.

这里的code,我把手表:

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

我只是想起那里一定是要做到这一点比我守着UI弄脏code用更清洁的方式是如果(dirtyCount> 0)...

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

,然后当第一$腕表火灾,做

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天全站免登陆