I'm implementing a solution for focusing an element, proposed here.
It works fine for a html input, but does not work for a custom directive. Here is the plunk to demonstrate the issue. Clicking "Focus input" upon page load focuses text input next to the button, but clicking "Focus control" doesn't focus text input next to it. Actually, the reason for this is that the $watch
function is not called when clicking "Focus control" button (can be seen in browser console).
The question is why that $watch
function is not called?
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.inputFocused = false;
$scope.controlFocused = false;
});
app.directive('focusedWhen', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.focusedWhen, function (value) {
console.log('focusedWhen', value);
if (value) {
element.find('input[type=text]').andSelf().trigger('focus');
}
});
}
};
});
app.directive('myControl', function () {
return {
restrict: 'E',
scope: {},
template: '<span><input type="text"></span>',
link: function (scope, element, attrs) {
}
};
});
HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery@*" data-semver="1.7.2" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" data-semver="1.0.7"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div>
<button ng-click="inputFocused = true;">Focus input</button>
<input type="text" focused-when="inputFocused" />
</div>
<div>
<button ng-click="controlFocused = true;">Focus control</button>
<my-control focused-when="controlFocused"></my-control>
</div>
</body>
</html>