Access Code:
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>
JavaScript
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>
JavaScript
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';
}
I want to click a button to set the input element's value, which should be retrievable by AngularJS using ng-model or a scope object.
However, when changing the element's value with
document.querySelector('#angular').value = 'testg';
,
neither AngularJS $watch nor bind function can capture the value change event. If words are typed into the input element using the keyboard, both functionalities work.
How can I detect changes in the input element's value when setting it in this manner in AngularJS?