【问题标题】:Wrapping angular-ui-typeahead breaks the on-select callback包装 angular-ui-typeahead 会破坏 on-select 回调
【发布时间】:2013-12-03 00:51:24
【问题描述】:

我正在尝试用我自己的指令包装 AngularUI 的 typeahead directive,以便我可以打包一些共享数据/行为以便在我的应用程序中更轻松地重用:Plunker

onSelect回调中,为什么超时后才显示正确的值?

作为参考,这在没有包装指令的情况下可以正常工作:Plunker

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui angular-ui-bootstrap angular-ui-typeahead


    【解决方案1】:

    在隔离范围指令内使用=,以便仅在模型更新后调用绑定函数:

    scope : {
        selectedModel : "=",
        onSelect : "="
    }
    

    Plunker

    【讨论】:

    • 实际上,使用 '=' 会导致 onSelect 无限循环(在 this.onSelect 中添加一个 console.log 来观察)。传入 on-select="ctrl.onSelect" 会停止无限循环,但我们会回到第一格。另外,我不喜欢在没有括号的情况下声明函数,因为它与常规方式不同。
    【解决方案2】:

    您必须在指令中使用 & 并在 html 中传递项目。来自Angular Docs“& 绑定允许指令在特定时间触发原始范围上下文中表达式的评估。允许任何合法的表达式,包括包含函数调用的表达式。因此, & 绑定非常适合将回调函数绑定到指令行为。”

    指令中的隔离范围:

    scope: { 
    onSelect: '&'
    }
    

    HTML

    <input autocomplete="off"
    placeholder="Enter &ldquo;jo&rdquo; and pick something"
    ng-model="selectedModel"
    typeahead="v as v.name for v in vendors | filter:$viewValue"
    typeahead-on-select="onSelect({item: $item})" />
    

    回调函数应该接受一个项目

    function myCallback(item) {
    console.log(item);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多