I am trying to set focus on an input field via a custom directive on a form. This works fine when using the template property in the directive. But when I move the template into a separate html file via templateUrl
, element.find()
does not find my input fields any more:
The code goes as follows:
<!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="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form get-input-by-id="input2">
<my-input id="input1"></my-input>
<my-input id="input2"></my-input>
</form>
</body>
</html>
The js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
app.directive('getInputById', function() {
return {
link: function (scope, element, attrs) {
//console.log(element);
var toFocus = element.find('input');
console.log(toFocus);
toFocus[1].focus();
}
}
});
app.directive('myInput', function() {
return {
restrict: 'E',
scope: {
id: "@id",
},
// this is not working
templateUrl: 'template.html',
// this is working
//template: '<div><input id="{{id}}"/></div>',
link: function (scope, element, attrs) {
}
}
});
And the template:
<div>
<input id="{{id}}"/>
</div>
I added both working and not working plunkers: