【发布时间】:2015-06-16 11:50:38
【问题描述】:
我有一个指令,它将根据值获取/设置元素的焦点。
当元素被聚焦或模糊时,指令将更新布尔值。但是,有时我只想在满足条件时设置焦点并且我使用不可分配的值,这会引发此错误:
Error: [$compile:nonassign] Expression '$last && !domain.url' used with directive 'focusWhen' is non-assignable!
WORKING DEMO HERE(检查控制台是否有错误)
我明白它为什么会抛出错误,但是我如何才能从指令内部检测到不可赋值的值,然后阻止它附加在焦点更改时尝试分配值的焦点/模糊事件? em>
这是一个使用不可赋值的指令的示例。在这种情况下,如果它也是一个空白值,它会将焦点设置在转发器中的最后一项上
<div ng-repeat="domain in domainList">
<input type="text" ng-model="domain.url" focus-when="$last && !domain.url"/>
</div>
这是指令代码;
testApp.directive("focusWhen", ["$timeout", function ($timeout) {
function getLink($scope, $element) {
$scope.$watch("focusWhen", function (val) {
//only focus when needed and when this element doesn't already have focus
if (val && $element[0] !== document.activeElement) {
//Small delay needed before we can get focus properly
$timeout(function () {
$element.focus();
});
}
});
$element.on("blur.focusWhen", function () {
if ($scope.focusWhen) {
$timeout(function () {
$scope.focusWhen = false;
});
}
});
$element.on("focus.focusWhen", function () {
if (!$scope.focusWhen) {
$timeout(function () {
$scope.focusWhen = true;
});
}
});
}
return {
restrict: "A",
scope: {
focusWhen: "="
},
link: getLink
};
}]);
【问题讨论】:
标签: angularjs angularjs-directive