我正在写一个<password>
指令将包含 <input>
随后是 <span>
(允许用户显示/隐藏密码的图标)。是否可以让 Angular 用这两个元素替换 HTML 中的指令元素,并将指令元素上存在的所有属性应用到 <input>
元素?
所以:
<password ng-model="myVar" ng-change="myTrigger" ng-whatever="myWhatever"></password>
会变成:
<span>
<input type="password" ng-model="myVar" ng-change="myTrigger" ng-whatever="myWhatever"/>
<span ng-click="togglePasswordVisibility()">show/hide</span>
</span>
并且如果用户将任何其他属性添加到 <password>
将它们应用到 <input>
.
最佳答案
您必须在元素编译时手动执行此操作:
.directive('password', function($compile) {
return {
restrict: 'E',
replace: true,
template: '<span>' +
'<input type="password" />' +
'<span ng-click="togglePasswordVisibility()">show/hide</span>' +
'</span>';
compile: function($element, $attr) {
return function($scope, $element, $attr) {
var input = $element.find('input[type=password]'),
attributes = $element.prop("attributes");
angular.forEach(attributes, function() {
input.attr(this.name, this.value);
});
$compile($input)($scope);
}
}
}
});
还没有测试过,但我认为这是可行的方法(可能不是最好的方法)
关于javascript - 我可以用两个元素替换 Angular 指令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24283936/