I have a directive that will get/set focus on an element depending on a value.
When the element is focused or blurred the directive will update the boolean value. However, sometimes I only want to set the focus when a condition is met and I use a non-assignable value, which throws this error:
Error: [$compile:nonassign] Expression '$last && !domain.url' used with directive 'focusWhen' is non-assignable!
WORKING DEMO HERE (check the console for errors)
I understand why it's throwing an error, but how can I detect non-assignable values from inside the directive and then prevent it from attaching focus/blur events that attempt to assign the value when the focus changes?
Here's an example usage of the directive used with a non-assignable value. In this case, it would set the focus on the last item in the repeater if it is also a blank value
<div ng-repeat="domain in domainList">
<input type="text" ng-model="domain.url" focus-when="$last && !domain.url"/>
</div>
And here's the directive code;
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
};
}]);