online 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>
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'; }
I want to click a button to set the value of an input element, and angularjs (ng-model or scope object) can get it.
But document.querySelector('#angular').value = 'testg';
change the value of the element in this way. Neither the angularjs $ watch function nor the bind function can receive a value change event. If you enter a few words into a keyboard input element, they both work.
How can I detect a change in the value of an input element at a given value this way in angularjs?