我有一个双向数据绑定(bind),它不会改变发送到指令的变量的值。
我的指令监视触发器并将焦点放在 associates 元素上(基于在 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);
});
}
});
}
}
});
在 HTML 中,我将其称为如下:
<input type="text" ng-model="item.value" focus-me="focusInput" />
当我第一次触发它时,它起作用了——因为
focusInput
变量切换其值。但是focusInput
在 Controller 范围内(指令之外)不会切换回 false
当指令完成时。此切换回
false
当我调用 scope.trigger = false
时应该会发生,假设我明白应该发生什么。缺少什么会导致双向绑定(bind)不将值推回传递给指令的变量?
更新 01:
为了发布问题,我删除了一小部分代码。 HTML 实际上如下所示:
<input type="text" ng-model="item.value" focus-me="focusInput" ng-if="item.condition != 'matches' && item.condition != 'does not match'" />
如果
input
字段隐藏然后重新显示(基于 ng-if
)指令将在第一次 focusInput
时正确提供焦点变化。之后它将再次停止工作......除非重复隐藏/显示过程。
最佳答案
您遇到的问题是在作用域内处理原始值( bool 值、整数等)时的常见问题。
我强烈建议阅读Understanding Scopes文章。 (简短的回答:原语在指令的隔离范围内被更改,并且不会在父范围的链上搜索,即您的 Controller 范围)。
至于如何解决您的情况,我建议使用点表示法并将您的原语存储在一个对象中,并将该对象绑定(bind)到您的指令:
scope: {
triggerObj: '=focusMe'
},
并确保指令中的触发器引用现在是
scope.triggerObj.trigger
.在您的 Controller 中有:
$scope.triggerObj = {};
$scope.triggerObj.trigger = true; //or false, what have you
拥有一个对象将确保两种方式绑定(bind)都可以工作。当你有时间的时候阅读上面的文章:)
关于javascript - 观察 bool 值时AngularJS指令双向数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265310/