I have a two-way data binding that is not altering the value of the variable sent to the directive.
My directive watches for a trigger and gives focus to the associates element (based on code found here at SO):
app.directive('focusMe', function ($timeout) {
return {
scope: {
trigger: '=focusMe'
},
link: function (scope, element, attrs) {
scope.$watch('trigger', function(value) {
console.log("directive value: " + value);
console.log("directive start: " + scope.trigger);
if (value === true) {
$timeout(function () {
element[0].focus();
scope.trigger = false;
console.log("directive end: " + scope.trigger);
});
}
});
}
}
});
In the HTML I call it as follows:
<input type="text" ng-model="item.value" focus-me="focusInput" />
When I trigger it for the first time, it works -- because the focusInput
variable switches its value. But focusInput
in the controllers scope (outside the directive) does not switch back to false
when the directive completes.
This switch back to false
should happen when I call scope.trigger = false
, assuming I understand what should be happening.
What is missing that would cause the two-way binding to not push the value back to the variable passed into the directive?
UPDATE 01:
For posting the question I removed a small bit of code. The HTML actually looks like this:
<input type="text" ng-model="item.value" focus-me="focusInput" ng-if="item.condition != 'matches' && item.condition != 'does not match'" />
If the input
fields hides and then is re-shown (based on the ng-if
) the directive will properly give focus the first time focusInput
changes. It will stop working again after that... unless the hide/show process is repeated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…