Mic*_* J. 156 jquery bind directive angularjs
我有这个简单的场景:
输入元素,其值由jQuery的val()方法更改.
我试图用jQuery设置的值更新角度模型.我试着编写一个简单的指令,但它并没有按照我的意愿行事.
这是指令:
var myApp = angular.module('myApp', []);
myApp.directive('testChange', function() {
return function(scope, element, attrs) {
element.bind('change', function() {
console.log('value changed');
})
}
})
Run Code Online (Sandbox Code Playgroud)
这是jQuery的一部分:
$(function(){
$('button').click(function(){
$('input').val('xxx');
})
})
Run Code Online (Sandbox Code Playgroud)
和HTML:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input test-change ng-model="foo" />
<span>{{foo}}</span>
</div>
</div>
<button>clickme</button>
Run Code Online (Sandbox Code Playgroud)
这是我尝试的小提琴:http:
//jsfiddle.net/U3pVM/743/
有人可以指点我正确的方向吗?
Ste*_*wie 319
ngModel侦听"input"事件,因此要"修复"您需要在设置值后触发该事件的代码:
$('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
});
Run Code Online (Sandbox Code Playgroud)
有关此特定行为的解释,请查看我之前给出的答案:" AngularJS如何在内部捕获'onclick','onchange'等事件? "
但不幸的是,这不是你遇到的唯一问题.正如其他帖子评论所指出的那样,以jQuery为中心的方法是完全错误的.有关更多信息,请查看以下文章:如果我有jQuery背景,我如何"在AngularJS中思考"?).
gin*_*man 59
希望这对某人有用.
我无法让jQuery('#myInputElement').trigger('input')事件被我的角度应用程序拿起.
然而,我能够angular.element(jQuery('#myInputElement')).triggerHandler('input')被接走.
Uto*_*pik 22
我不认为这里需要jQuery.
<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>
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
$scope.$watch('foo', function(newValue, oldValue) {
console.log(newValue);
console.log(oldValue);
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*dis 20
接受inputjQuery 触发事件的答案对我不起作用.创建一个事件并使用本机JavaScript进行调度就可以了.
$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));
Run Code Online (Sandbox Code Playgroud)
小智 17
您必须使用以下代码才能更新特定输入模型的范围,如下所示
$('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;
});
});
Run Code Online (Sandbox Code Playgroud)
我通过在操作按钮上添加监听器来仅对控制器初始化进行了修改:
$(document).on('click', '#action-button', function () {
$timeout(function () {
angular.element($('#input')).triggerHandler('input');
});
});
Run Code Online (Sandbox Code Playgroud)
其他解决方案在我的情况下不起作用.
| 归档时间: |
|
| 查看次数: |
172563 次 |
| 最近记录: |