我有这个自定义指令:
eDiscovery.directive('customHighlightUsername', function () {
return {
restrict: 'A',
link: function ($scope, elem, attrs) {
elem.bind('change', function () {
console.log('bind works'); // this does not work
});
elem.on('blur', function () {
console.log('blur works'); // this works
});
elem.on('change', function () {
console.log('change works'); // this does not work
});
}
}
});
这是我的HTML:
<input custom-highlight-username
type="text"
style="display: initial;"
ng-model="assignSelectedQuestionsInput"
placeholder="Assign users to selected questions:"
class="form-control">
无论出于何种原因,on('blur')
回调都在我的指令中工作,但on('change')
和bind('change')
回调不会按预期触发。如您所见,这是一个文本输入字段 - 当在字段中输入新字符时,我希望更改回调触发。
有谁知道为什么会这样?
答案 0 :(得分:0)
您可以使用此runnable demo fiddle中的$scope.$watch
来实现此目的。这是AngularJS在ngModel
不可用时收听ng-change
更改的常用方法。
<div ng-controller="MyCtrl">
<input custom-highlight-username
type="text"
style="display: initial;"
ng-model="assignSelectedQuestionsInput"
callback="someFunction(param)"
placeholder="Assign users to selected questions:"
class="form-control">
</div>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.someFunction = function (someParam) {
console.log(someParam);
}
});
myApp.directive('customHighlightUsername', function ($timeout) {
return {
restrict: 'A',
scope: {
"model": '=ngModel',
"callbackFunction": '&callback'
},
link: function (scope, elem, attrs) {
scope.$watch('model', function (newValue, oldValue) {
if (newValue && oldValue) {
console.log('changed');
scope.callbackFunction({ param: 'log test'});
}
});
elem.on('blur', function () {
console.log('blur works');
});
}
}
});
答案 1 :(得分:0)
根据您发布的内容,更改事件应该没问题。现在,当代码更新值时,不会触发更改事件。
function customHighlightUsername () {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.bind("change", function() {
console.log('change');
});
elem.bind("blur", function() {
console.log('blur');
});
elem.bind("input", function() {
console.log('input');
});
}
}
}
angular.module('myApp', []);
angular
.module('myApp')
.directive('customHighlightUsername', customHighlightUsername);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<input custom-highlight-username type="text" />
</div>