【发布时间】:2014-07-03 16:22:21
【问题描述】:
我正在尝试通过表单上的自定义指令将焦点设置在输入字段上。在指令中使用模板属性时,这可以正常工作。但是当我通过templateUrl 将模板移动到单独的html 文件中时,element.find() 不再找到我的输入字段:
代码如下:
<!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>
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) {
}
}
});
还有模板:
<div>
<input id="{{id}}"/>
</div>
我添加了工作和不工作的 plunker:
【问题讨论】:
标签: javascript angularjs