在AngularJS中,在指令模板中使用另一个指令。

3

我对AngularJS还比较陌生,正在尝试在一个指令内部实现另一个指令。我有一个子指令basetext,它处理基本的输入事件,还有一个myTextbox,它处理与输入相关的其他任务。我制作了一个简单的plunker来演示我的问题。我已经实现了以下内容:

html中:

<div my-textbox placeholder="'Input the value'" caption="Name:"></div>

myTextbox指令模板函数中:

template: function (elem, attrs) {
        return ("<label>" + attrs.caption + "</label>\
                 <input class='inputText' basetext='' " + "placeholder=" + attrs.placeholder +"/>");
},

以及我的 basetext 指令:

app.directive("basetext", function () {
    return {
        restrict:'A',
        scope:{}
        template: "<input ng-focus='isFocus()' ng-blur='isBlur()'/>",
        link: function (scope, element, attrs) {

            scope.isBlur = function () {
                alert("is blurred");
            }
            scope.isFocus = function () {
                alert("is focused");
            }
        }
    }
});

问题在于basetext指令的blur事件和focus事件根本不起作用。有没有解决这个问题的建议?谢谢。


1
只需查看生成的HTML。在应用此指令的输入中,将“basetext”放入带有事件的输入中。 - Grundy
好的,我会尝试。 - Rebel
1个回答

1
检查元素,你会看到。

enter image description here

basetext的模板在输入标签内,这是无效的。

你需要在basetext指令上加上replace: true属性,这样它就会替换子指令模板的元素。

app.directive("basetext", function () {
    return {
        restrict:'A',
        replace: true,
        scope:{},
        template: "<input ng-focus='isFocus()' ng-blur='isBlur()'/>",
        link: function (scope, element, attrs) {

            scope.isBlur = function () {
                alert("is blurred");
            }
            scope.isFocus = function () {
                alert("is focused");
            }
        }
    }
});

这里是DEMO

2
有趣,我认为replace应该替换元素,而不是扩展它 :-) - Grundy
1
很棒,很高兴能帮到你 :) - Kalhan.Toress

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接