微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在angularjs中设置值时检测输入元素更改

在线代码

http://jsfiddle.net/mb98y/309/

HTML

<div ng-app="myDirective" ng-controller="x">
    <input id="angular" type="text" ng-model="data.test" my-directive>
</div>
    <button onclick="document.querySelector('#angular').value = 'testg';">click</button>

JS

angular.module('myDirective',[])
    .directive('myDirective',function () {
    return {
        restrict: 'A',link: function (scope,element,attrs) {
            scope.$watch(attrs.ngModel,function (v) {
                //console.log('value changed,new value is: ' + v);
                alert('value change: ' + scope.data.test);
            });
        }
    };
});

function x($scope) {
    //$scope.test = 'value here';
    $scope.data = {
        test: 'value here'
    }
}

http://jsfiddle.net/mb98y/310/

HTML

<div ng-app="myDirective" ng-controller="x">
<input id="angular" type="text" my-directive="test">{{test}}</div>
<button onclick="document.querySelector('#angular').value =  'testg';">click</button>

JS

angular.module('myDirective',scope: {
            myDirective: '='
        },attrs) {
            // set the initial value of the textBox
            element.val(scope.myDirective);
            element.data('old-value',scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective',function (val) {
                element.val(scope.myDirective);
            });

            // on blur,update the value in scope
            element.bind('propertychange keyup change paste',function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed,new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value',element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

我想点击按钮设置输入元素值和angularjs(ng-model或范围对象)可以得到它.

但是,document.querySelector(‘#angular’).value =’testg’;

以这种方式改变元素值,angularjs $watch和bind函数都不能获得值改变事件.如果你通过键盘在输入元素中输入一些单词,它们都可以工作.

在angularjs中以这种方式设置值时,如何检测输入元素值的变化?

解决方法

首先,这里是双向数据绑定,以避免这种情况.
<input ng-model='ctrl.field' />

 <button ng-click='ctrl.field = "new value"'>change</button>

其次,ng-change指令与ng-model一起使用,当模型中的值发生变化时,可以使用ng-change指令执行某些操作.

<input ng-model='ctrl.field' ng-change='alert("changed!")' />

如果您仍希望直接使用DOM更改角度之外的值,则只需触发角度侦听的事件 – 模糊或按键

<button ng-click='$("#id").val(a); $("#id").trigger("blur")'>change</button>

要么

<button ng-click='angular.element("#id").val(a); angular.element("#id").trigger("blur")'>change</button>

原文地址:https://www.jb51.cc/js/159501.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐