0

http://plnkr.co/edit/VAE43y5cagCF8jq5AlaY?p=preview

Within the directive, I'm using scope.$apply(). However, if you click too quickly it changes the value but not the visual affect. This problem seems to be related to timing. If I load the page and let it sit for 2 seconds the first click changes the value. However, if I try to click it too quickly, it'll change the value without changing the visuals.

Can anyone explain this? I'm thinking it might be mid-digest cycle or something like that, but can't say for sure and I'm not sure what to do about it...

            //toggle the state when clicked
            el.bind('click', function () {
                scope.$apply(function () {
                  var getter=$parse(attrs.ngModel);
                  var setter=getter.assign;
                  setter(scope,!getter(scope));
                    //scope[attrs.ngModel] = !scope[attrs.ngModel];
                    if (el.hasClass('on')) {
                        off();
                    } else {
                        on();
                    }
                });
            });
4

1 回答 1

1

我会使用控制器$viewValue而不是使用attrs[ngModel]. 更新控制器时效率更高scopes。因此,您可以设置新值,而不是使用 parse 和其他东西进行解析和分配。

首先我们需要ngModel控制器。

require: '^ngModel',

然后我们简单地设置作用域的新值。

el.bind('click', function () {
    scope.$apply(function () {
         ctrl.$setViewValue(!ctrl.$viewValue);
    });
});

我们 $watch 模型属性。

scope.$watch(attrs.ngModel, function (oldValue, newValue) {
   if (newValue) {
      off();
   } else {
      on();
   }
});

我叉了你的plunkr

于 2013-08-26T18:51:25.433 回答