使用 jQuery 设置输入值后更新 Angular 模型 [英] Update Angular model after setting input value with jQuery

查看:29
本文介绍了使用 jQuery 设置输入值后更新 Angular 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的场景:

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

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

指令如下:

var myApp = angular.module('myApp', []);myApp.directive('testChange', function() {返回函数(范围,元素,属性){element.bind('change', function() {console.log('值改变');})}})

这是jQuery部分:

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

和 html:

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

<button>clickme</button>

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

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

解决方案

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

$('button').click(function(){var input = $('input');input.val('xxx');input.trigger('输入');//用于 Chrome/Firefox/Edgeinput.trigger('改变');//用于 Chrome/Firefox/Edge + IE11});

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

<小时>

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

I have this simple scenario:

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

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.

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:

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

and 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/

Can someone please point me in the right direction?

解决方案

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

$('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'?"


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 设置输入值后更新 Angular 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆