指令“链接”不适用,如我所愿

directive "link" doesn't apply as I want it

本文关键字:不适用 链接 指令      更新时间:2023-09-26

好的,我得到了一个页面,其中包含一些使用角度x可编辑管理的输入。

小提琴

以下指令:

treeView.directive('selectWhenEditing',function(){
    var linkFunction = function(scope,startingelem,attr)
    {
        console.log(startingelem[0]);
        console.log (startingelem[0].querySelector('.editable'));
        angular.element(startingelem[0].querySelector('.editable')).on('click',function(){   
            //console.log(startingelem[0]);
            angular.element(startingelem[0].querySelector('.editable-input').select());            
        });
    };
    return{
        restrict: 'AEC',
        link:linkFunction
    };}
);

应该在我单击可编辑元素时选择文本。

这是页面的代码:

<tr ng-repeat="properties in elementToEdit" ng-if="fieldsSettings[$index][1]==1">
            <td>
                    {{ fieldsSettings[$index][0] }}
            </td>
            <td data-select-when-editing>                                    
                <span editable-text="properties.prop" onbeforesave="" ng-if="fieldsSettings[$index][2]== 'text'">
                            {{ properties.prop || 'empty' }}               
                </span>
                <span editable-select="properties.prop" onbeforesave="" ng-if="fieldsSettings[$index][2]== 'select'" e-ng-options="s.value as s.text for s in fieldsSettings[$index][3]">
                            {{ selectElement(properties.prop,$index) || 'empty' }}               
                </span>
            </td>                                
    </tr>

这就是相关的编译 HTML:

<tr class="ng-scope" ng-if="fieldsSettings[$index][1]==1" ng-repeat="properties in elementToEdit">
    <td class="ng-binding"> Name </td>
    <td data-select-when-editing="">
        <span class="ng-scope ng-binding editable editable-click" ng-if="fieldsSettings[$index][2]== 'text'" onbeforesave="" editable-text="properties.prop"> Food </span>
    </td>
</tr>

指令按照我的意愿触发(例如:预期的次数(。第一个控制台.log按预期记录调用 TD 元素。但是第二个是空的,因为它从未在此TD中找到元素".editable",因此显然从未选择文本(未应用事件"on"(。

我在另一个页面/模块中做了完全相同的事情,效果很好。我正在比较代码,但找不到区别。

你们看到了什么?

正如文档中所说,jqLite 的find()函数是"仅限于按标签名称查找",这意味着您不能使用它按类选择元素 - 因此您需要改用querySelector。请注意,您还需要startingelem[0],而不仅仅是使用它时startingelem

我不得不使用 angular.element 来获取用于on()绑定的 jqLite 对象(您可以在那里使用 plainJS,如下所示(,所以它看起来有点丑陋:

angular.element(startingelem[0].querySelector(".editable")).on('click',function(){
    startingelem[0].querySelector('.editable-input').select();
});

这是完整的工作版本:http://jsfiddle.net/ar7znuz5/


使用addEventListener的纯JS版本:

startingelem[0].querySelector(".editable").addEventListener('click',function(){
    startingelem[0].querySelector('.editable-input').select();            
});

和完整的工作版本:http://jsfiddle.net/ar7znuz5/1/


最后一个版本,带有选择和更新的原始代码:http://jsfiddle.net/ar7znuz5/7/