使用 jQuery 设置输入值后更新 Angular 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17109850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:27:59  来源:igfitidea点击:

Update Angular model after setting input value with jQuery

jqueryangularjsbinddirective

提问by Michal J.

I have this simple scenario:

我有一个简单的场景:

Input element which value is changed by jQuery's val() method.

通过 jQuery 的 val() 方法更改值的输入元素。

I am trying to update the angular model with the value that jQuery set. I tried to write a simple directive, but it's not doing what I want.

我正在尝试使用 jQuery 设置的值更新角度模型。我试图编写一个简单的指令,但它没有做我想要的。

Here's the directive:

这是指令:

var myApp = angular.module('myApp', []);
myApp.directive('testChange', function() {
    return function(scope, element, attrs) {        
        element.bind('change', function() {
            console.log('value changed');
        })
    }
})

this is the jQuery part:

这是 jQuery 部分:

$(function(){
    $('button').click(function(){
        $('input').val('xxx');
    })
})

and html:

和 html:

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <input test-change ng-model="foo" />
        <span>{{foo}}</span>
    </div>
</div>

<button>clickme</button>

Here is the fiddle with my try:
http://jsfiddle.net/U3pVM/743/

这是我尝试的小提琴:http:
//jsfiddle.net/U3pVM/743/

Can someone please point me in the right direction?

有人可以指出我正确的方向吗?

回答by Stewie

ngModel listens for "input" event, so to "fix" your code you'd need to trigger that event after setting the value:

ngModel 侦听“输入”事件,因此要“修复”您的代码,您需要在设置值后触发该事件:

$('button').click(function(){
    var input = $('input');
    input.val('xxx');
    input.trigger('input'); // Use for Chrome/Firefox/Edge
    input.trigger('change'); // Use for Chrome/Firefox/Edge + IE11
});

For the explanation of this particular behaviour check out this answer that I gave a while ago: "How does AngularJS internally catch events like 'onclick', 'onchange'?"

有关此特定行为的解释,请查看我不久前给出的这个答案:“ AngularJS 如何在内部捕获诸如 'onclick'、'onchange' 之类的事件?



But unfortunately, this is not the only problem you have. As pointed out with other post comments, your jQuery-centric approach is plain wrong. For more info take a look at this post: How do I “think in AngularJS” if I have a jQuery background?).

但不幸的是,这并不是您遇到的唯一问题。正如其他帖子评论所指出的那样,您以 jQuery 为中心的方法是完全错误的。有关更多信息,请查看这篇文章:如果我有 jQuery 背景,我如何“在 AngularJS 中思考”?)。

回答by ginman

Hope this is useful for someone.

希望这对某人有用。

I was unable to get the jQuery('#myInputElement').trigger('input')event to be picked up my angular app.

我无法在jQuery('#myInputElement').trigger('input')我的 angular 应用程序中获取该事件。

I was however, able to get angular.element(jQuery('#myInputElement')).triggerHandler('input')to be picked up.

然而,我能够angular.element(jQuery('#myInputElement')).triggerHandler('input')被接走。

回答by Utopik

I don't think jQuery is required here.

我认为这里不需要 jQuery。

You can use $watchand ng-clickinstead

您可以使用$手表NG-单击代替

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <input test-change ng-model="foo" />
    <span>{{foo}}</span>

    <button ng-click=" foo= 'xxx' ">click me</button>
    <!-- this changes foo value, you can also call a function from your controller -->
  </div>
</div>

In your controller :

在您的控制器中:

$scope.$watch('foo', function(newValue, oldValue) {
  console.log(newValue);
  console.log(oldValue);
});

回答by Martins Balodis

The accepted answer which was triggering inputevent with jQuery didn't work for me. Creating an event and dispatching with native JavaScript did the trick.

input使用 jQuery触发事件的公认答案对我不起作用。创建一个事件并使用原生 JavaScript 进行调度就成功了。

$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));

回答by jayM

You have to use the following code in order to update the scope of the specific input model as follows

您必须使用以下代码来更新特定输入模型的范围,如下所示

$('button').on('click', function(){
    var newVal = $(this).data('val');
    $('select').val(newVal).change();

    var scope = angular.element($("select")).scope();
    scope.$apply(function(){
        scope.selectValue = newVal;
    });
});

回答by Ebru Yener

I made modifications on only controller initialization by adding listener on action button:

我通过在操作按钮上添加侦听器仅对控制器初始化进行了修改:

$(document).on('click', '#action-button', function () {
        $timeout(function () {
             angular.element($('#input')).triggerHandler('input');
        });
});

Other solutions did not work in my case.

其他解决方案在我的情况下不起作用。

回答by Khawaja Asim

I know it's a bit late to answer here but maybe I may save some once's day.

我知道在这里回答有点晚了,但也许我可以节省一些时间。

I have been dealing with the same problem. A model will not populate once you update the value of input from jQuery. I tried using trigger events but no result.

我一直在处理同样的问题。一旦您更新来自 jQuery 的输入值,模型将不会填充。我尝试使用触发事件但没有结果。

Here is what I did that may save your day.

这是我所做的,可以挽救你的一天。

Declare a variable within your script tag in HTML.

在 HTML 中的脚本标记中声明一个变量。

Like:

喜欢:

<script>
 var inputValue="";

// update that variable using your jQuery function with appropriate value, you want...

</script>

Once you did that by using below service of angular.

一旦你通过使用下面的 angular 服务来做到这一点。

$window

$窗口

Now below getData function called from the same controller scope will give you the value you want.

现在,从同一控制器范围调用的 getData 函数将为您提供所需的值。

var myApp = angular.module('myApp', []);

app.controller('imageManagerCtrl',['$scope','$window',function($scope,$window) {

$scope.getData = function () {
    console.log("Window value " + $window.inputValue);
}}]);

回答by dav_i

I've written this little plugin for jQuery which will make all calls to .val(value)update the angular element if present:

我已经为 jQuery 编写了这个小插件,它会调用所有.val(value)更新 angular 元素(如果存在):

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value)updates should now play nice.

只需在 jQuery 和 angular.js 之后弹出这个脚本,val(value)更新现在应该可以正常运行了。



Minified version:

缩小版:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);


Example:

例子:

// the function
(function($, ng) {
  'use strict';
  
  var $val = $.fn.val;
  
  $.fn.val = function (value) {
    if (!arguments.length) {
      return $val.call(this);
    }
    
    var result = $val.call(this, value);
    
    ng.element(this[0]).triggerHandler('input');
    
    return result;
    
  }
})(window.jQuery, window.angular);

(function(ng){ 
  ng.module('example', [])
    .controller('ExampleController', function($scope) {
      $scope.output = "output";
      
      $scope.change = function() {
        $scope.output = "" + $scope.input;
      }
    });
})(window.angular);

(function($){  
  $(function() {
    var button = $('#button');
  
    if (button.length)
      console.log('hello, button');
    
    button.click(function() {
      var input = $('#input');
      
      var value = parseInt(input.val());
      value = isNaN(value) ? 0 : value;
      
      input.val(value + 1);
    });
  });
})(window.jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="example" ng-controller="ExampleController">
  <input type="number" id="input" ng-model="input" ng-change="change()" />
  <span>{{output}}</span>
  <button id="button">+</button>
</div>

回答by William

If you are using IE, you have to use: input.trigger("change");

如果您使用的是 IE,则必须使用: input.trigger("change");

回答by Azeez

add .change()after setting the value.

.change()设置值后添加。

example:('id').val.('value').change();

例子:('id').val.('value').change();

also don't forget to add onchangeor ng-changetag in html

也不要忘记在 html 中添加onchangeng-change标记