【发布时间】:2014-07-11 17:55:14
【问题描述】:
在线代码:
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', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, 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 or scope object)可以得到它。
但是,document.querySelector('#angular').value = 'testg';
以这种方式改变元素值,angularjs $watch 和 bind 函数都不能获取值改变事件。如果您通过键盘在输入元素中输入一些单词,它们都可以工作。
在angularjs中以这种方式设置值时如何检测输入元素值的变化?
【问题讨论】:
标签: javascript angularjs