标签的属性在角度方向上不起作用

Attribute of label not working in angular directive?

本文关键字:方向 不起作用 属性 标签      更新时间:2024-01-15

我正在努力学习如何使用角度指令,到目前为止取得了成功。我只有一个小问题无法解决。

在我的指令中,我在输入字段的id的相同值上获得了一个for属性集。但是,点击标签并不能使输入控件像正常工作那样聚焦。

我在一些示例代码中解决了这个问题:

<div ng-app='test' ng-controller='testCtrl'>
    <label for="test1">Testlabel 1</label><br>
    <input id="test1" type="text"></input><br>
    <my-input id="test2" 
              label="Testlabel 2" 
              placeholder="enter somthing"
              text="testVar"></my-input><br>
    <span>{{testVar}}</span>
</div>

和javascript:

angular.module('test', [])
.directive('myInput', function() {
    return {
        restrict: 'E',
        template: '<label for={{id}}>{{label}}</label><br>' +
                  '<input id={{id}} type="text" ' +
                  ' placeholder={{placeholder}} ng-model="text" />',
        scope: {
            id: "@",
            label: "@",
            placeholder: "@",
            text: "="
        }
   }
})
.controller('testCtrl', ['$scope', function($scope) {
    $scope.testVar = 'testing';
}]);

jsfiddle中的相同代码:http://jsfiddle.net/U92em/

我犯了什么错误导致了我的问题,我该如何解决?

您的"包装器"也有相同的id,这并不好。您可以在link函数中删除它,方法如下:

 link: function(scope,el,attrs){
     el.removeAttr("id");
 }

工作:http://jsfiddle.net/cherniv/5u4Xp/

或者在compile功能中(感谢Florent):

 compile: function(el){
     el.removeAttr("id")
 }

示例:http://jsfiddle.net/cherniv/7GG6k/