Javascript AngularJs-操作链接函数内的模板
我有一个类似这样的指令Javascript AngularJs-操作链接函数内的模板,javascript,jquery,angularjs,templates,Javascript,Jquery,Angularjs,Templates,我有一个类似这样的指令 interface IMyDirectiveScope extends ng.IScope { emptyOption: boolean; foo: boolean; } class MyDirective implements IMyDirective { require: string = 'ngModel'; restrict: string = "AE";
interface IMyDirectiveScope extends ng.IScope {
emptyOption: boolean;
foo: boolean;
}
class MyDirective implements IMyDirective {
require: string = 'ngModel';
restrict: string = "AE";
replace: boolean = true;
transclude: boolean = true;
scope = {
foo: '=',
};
template: string = '<select class="something" ng-options="something"></select>';
link = ($scope: IMyDirectiveScope , $element, $attrs, ngModelCtrl: ng.INgModelController) => {
$scope.emptyOption = !(<any>$attrs).required;
if ($scope.emptyOption) {
var el = angular.element(this.template);
var elementHtml = this.$compile('<option value="">-</option>')($scope);
angular.element(el).append(elementHtml);
}
};
接口IMyDirectiveScope扩展了ng.IScope{
空选项:布尔;
foo:布尔;
}
类MyDirective实现IMyDirective{
require:string='ngModel';
限制:string=“AE”;
替换:布尔值=真;
转移:布尔值=真;
范围={
foo:“=”,
};
模板:字符串=“”;
link=($scope:IMyDirectiveScope$element$attrs,ngModelCtrl:ng.INgModelController)=>{
$scope.emptyOption=!($attrs).必填;
if($scope.emptyOption){
var el=angular.element(此.template);
var elementHtml=this.$compile('-')($scope);
元素(el).append(elementHtml);
}
};
我的选项是在link函数中动态创建的,如果我的元素不需要一个选项,我想添加一个空选项,这就是为什么我试图附加这个
元素,但我找不到将它附加到template元素的方法。按照我现在的方式,var el得到了我想要的方式
更新:我又搜索了一点,我发现对于这种指令,我使用
replace
和transclude
来操作,我需要链接上的traclude函数
,尽管我不明白怎么做,但有什么帮助吗?我走对了吗?因为compile
对我没有帮助,我已经试过了。var el=angular.element($element);
或者仅仅是var el=$element
,您可以尝试这两种方法中的一种。是的,但这不是我的问题,因为使用$element或this.template都会得到相同的结果。var el=angular.element($element);
或只是var el=$element
,您可以尝试这两种方法中的一种。是的,但这不是我的问题,因为使用$element或this.template都会得到相同的结果