简体   繁体   English

Angular指令引发双向数据绑定

[英]Angular directive throws off two-way data binding

I'm adapting this jQuery autocomplete plugin into a directive - https://github.com/devbridge/jQuery-Autocomplete . 我正在将此jQuery自动完成插件改编为指令-https: //github.com/devbridge/jQuery-Autocomplete

I have a directive that works: 我有一个有效的指令:

App.directive('autocomplete', ->
  return {
    restrict: 'A',
    link: ($scope, elem, attr) ->
      console.log(attr.autocomplete)
      elem.autocomplete({
        serviceUrl: '/videos/autocomplete/' + attr.autocomplete
      })
  }
)

However, when I select something in the autocomplete list, the two way data-binding messes up, and only the input is updated. 但是,当我在自动完成列表中选择某项时,两种方式的数据绑定混乱了,只有输入被更新了。

Any ideas on how to fix this? 有想法该怎么解决这个吗?

Necroposting this one, because I think it could be useful for many people to know about this great post I'm referring to :) 对此死灵化 ,因为我认为这对许多人来说是有用的,我知道我指的是这一篇好文章:)

Angular has a way to observe changes in our objects that relies on the "turn-based" nature of JavaScript. Angular有一种方法来观察我们对象中的变化,该方法依赖于JavaScript的“基于回合”性质。 This is explained very clearly in this awesome article by Jim Hoskins . 吉姆霍斯金斯(Jim Hoskins)这篇很棒的文章对此进行了非常清楚的解释。

Basically, Angular checks for changes in cycles, but when something changes in between those cycles, it has no way to know that it needs to perform its checks again! 基本上,Angular检查周期中的变化,但是当这些周期之间发生某些变化时,它无法知道需要再次执行检查! (VERY simplicistic explaination; again, refer to the article ) (非常简单的解释;再次参考该文章

Bottom line, we need to inform it that we changed something, so let's say your selection triggers an handler() that performs an action() 最重要的是,我们需要通知它我们已更改了某些内容,因此,假设您的选择触发了一个执行action()handler() action()

You simply need to wrap the action into a $scope.$apply 您只需包裹action$scope.$apply

function handler(){
    $scope.$apply(function(){
        action();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM