用jQuery设置输入值后更新角模型 [英] Update Angular model after setting input value with jQuery
问题描述
我有这个简单的场景:结果
- 输入元件,它的价值是由jQuery的VAL()方法更改
I have this simple scenario:
- input element which value is changed by jQuery's val() method
我试图更新的值设置jQuery的角度模式。我试着写一个简单的指令,但它没有做我想要的。
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.
下面的指令:
var myApp = angular.module('myApp', []);
myApp.directive('testChange', function() {
return function(scope, element, attrs) {
element.bind('change', function() {
console.log('value changed');
})
}
})
这是jQuery的部分:
this is the jQuery part:
$(function(){
$('button').click(function(){
$('input').val('xxx');
})
})
和HTML:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input test-change ng-model="foo" />
<span>{{foo}}</span>
</div>
</div>
clickme
clickme
下面是我尝试小提琴:结果
http://jsfiddle.net/U3pVM/743/
Here is the fiddle with my try:
http://jsfiddle.net/U3pVM/743/
可有人请点我朝着正确的方向?谢谢你。
Can someone please point me in the right direction? Thanks.
推荐答案
ngModel监听输入事件,所以要修理你的code你需要设定值后触发事件:
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');
});
对于这个特定的行为结账这个答案,我给了前一阵子的解释:<一个href=\"http://stackoverflow.com/questions/15739960/how-does-angularjs-internally-catch-events-like-onclick-onchange/15740287#15740287\">How确实AngularJS内部捕获的事件,如的onclick,的onchange?
但不幸的是,这是不是你的唯一问题。与其它发表评论指出的那样,你的jQuery为中心的做法是完全错误的。欲了解更多信息看一看这个帖子:<一href=\"http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background\">How我认为AngularJS如果我有一个jQuery的背景是什么?)。
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设置输入值后更新角模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!