My aim is to apply focus on an input field using a custom directive within a form. Initially, everything was functioning correctly when utilizing the template property in the directive. However, upon transferring the template into a separate HTML file using templateUrl
, the element.find()
method could no longer locate my input fields:
The following code snippet illustrates this issue:
<!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="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31505f56445d50431f5b4271001f031f49">[email protected]</a>" 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 JavaScript part:
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 section is causing issues
templateUrl: 'template.html',
// This section works as intended
//template: '<div><input id="{{id}}"/></div>',
link: function (scope, element, attrs) {
}
}
});
The content of the template file:
<div>
<input id="{{id}}"/>
</div>
I have included links to both functional and non-functional versions of the plunkers for comparison: