【问题标题】:autocompelete in AngularJS and ng-grid在 AngularJS 和 ng-grid 中自动完成
【发布时间】:2023-03-23 07:08:01
【问题描述】:

此参考有助于使用标签制作指令“自动完成”。 Problems with jQuery autocomplete + AngularJS

但是,我有以下问题:

我知道为了在自动完成列表中选择后处理事件,应该使用 jqueryUI 提供的事件处理程序。

...
     link: function(scope, elem, attr, ctrl) {
                elem.autocomplete({
                        source: datasource,
                        select: function( event, ui ) {
                             console.log(ui.item.value); 
                             console.log(attrs.ngModel);
                             //but how can I change the value of this ngModel in scope?
                        }

                    });
     };

但是,在指令中,我如何影响该 ngModel 的值?我可以使用 attrs.ngModel 获取该 ngModel 的名称。(知道 ng-model 的名称是动态的,我可以使用 ui.item.value 获取该值)

有人知道吗?非常感谢!

【问题讨论】:

  • 值究竟是什么?
  • 嗨,贾斯汀,感谢您的回复。其实我可以得到ngModel的名字,但是想在directive里修改那个ngMoel的值。

标签: angularjs ng-grid


【解决方案1】:

不确定您是否已经在指令中定义了范围,但这里有一个示例:

myApp.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      ngModel: '='
    },
    link: function(scope, element, attrs) {
      // monitor plugin and set value to ngModel
      element.plugin({
        onChange: function(newValue) {
          scope.$apply(function() {
            scope.ngModel = newValue;
          });
        }
      });

      // monitor ngModel and set new value to element/plugin
      scope.$watch('ngModel', function(newValue, oldValue) {
        element.val(newValue);
      });
    }
  };
});

【讨论】:

  • 非常感谢我!这正是范围。$apply 我想要的
【解决方案2】:

好的,在玩了几个小时这个例子之后(我只是在学习角度) 我认为设置您需要的值如下:

ngModel.$setViewValue(elm.val());

特别是您的代码应如下所示:

require: 'ngModel',
 link: function(scope, elem, attr, ctrl) {
            elem.autocomplete({
                    source: datasource,
                    select: function( event, ui ) {
                         console.log(ui.item.value); 
                         console.log(attrs.ngModel);

                         ctrl.$setViewValue(elem.val());

                         //but how can I change the value of this ngModel in scope?
                    }

                });
 };

所以我测试了它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2014-07-04
    • 2015-02-09
    • 2017-09-10
    相关资源
    最近更新 更多