简体   繁体   English

在AngularJS中调用jQuery插件函数

[英]Call jQuery plugin function in AngularJS

I am use jQuery plugin select2 and want call select2 function in AngularJS. 我正在使用jQuery插件select2,并希望在AngularJS中调用select2函数。 I know that can use angular-ui/ui-select , but page design require jQuery plugin select2. 我知道可以使用angular-ui / ui-select ,但是页面设计需要jQuery插件select2。

I want to change the value in the model Angular and change the value of the select2. 我想更改模型Angular中的值并更改select2的值。

I create Angular directive and I want to call select2 function, but do not know how to implement it correctly: 我创建了Angular指令,我想调用select2函数,但不知道如何正确实现它:

angular.module("myModule").directive("select2Value", [
  function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        scope.$watch(function() {
          element.select2().val(ngModel.$modelValue).change();
        });
      }
    };
  }
]);

I have this error: 我有这个错误:

Error: [$rootScope:inprog] $digest already in progress

For fix this error I am use this solution: https://stackoverflow.com/a/36219812/6746305 : 为了解决此错误,我使用以下解决方案: https : //stackoverflow.com/a/36219812/6746305

angular.module("myModule").directive("select2Value", [
  "$timeout", function($timeout) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        var timeout;
        changeValue(function() {
          element.select2().val(ngModel.$modelValue).change();
        });
        timeout = void 0;
        scope.$watch(function() {}, function(newVal, oldVal) {
          if (timeout) {
            $timeout.cancel(timeout);
          }
          timeout = $timeout(changeValue, 1000);
        });
      }
    };
  }
]);

But this not work: I am change value in Model Angular, but this value not change in select2. 但这不起作用:我在Model Angular中更改了值,但在select2中却没有更改。

I am find solution for change value in jQuery: 我在jQuery中找到更改值的解决方案:

angular.module("myModule").directive("select2Value", [
  "$timeout", function($timeout) {
    return {
      restrict: 'A',
      priority: 0,
      link: function(scope, element, attr, ngModel) {
        return scope.$watch(attr.ngModel, function(value) {
          return $timeout(function() {
            return element.val(value).change();
          });
        });
      }
    };
  }
]);

Solution find here (thank you this blog): http://blog.virtualzone.de/2015/08/angularjs-watching-for-changes-in-ng-model-and-determine-linked-dom-element.html 解决方案可在此处找到(感谢此博客): http : //blog.virtualzone.de/2015/08/angularjs-watching-for-changes-in-ng-model-and-determine-linked-dom-element.html

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

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