【问题标题】:Use one directive inside another directive template in Angularjs在 Angularjs 的另一个指令模板中使用一个指令
【发布时间】:2023-03-29 02:51:01
【问题描述】:

我对 Angularjs 很陌生,并尝试在另一个指令中实现一个指令。我有一个子指令basetext 处理基本输入事件,myTextbox 处理与输入相关的其他任务。我做了一个simple 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 事件根本不起作用。有什么建议可以解决这个问题吗?谢谢

【问题讨论】:

  • 只看生成的html。 basetextinput 与应用此指令的输入内的事件一起放置
  • 好的,我会试试的。

标签: javascript angularjs angularjs-directive


【解决方案1】:

检查元素,你会看到

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

您需要将replace: true, 属性放在basetext 指令上,因为它将替换子指令模板的元素。

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

【讨论】:

  • 有趣,我认为 replace 应该 替换 元素,而不是 extend 它:-)
  • 很好,很高兴为您提供帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
相关资源
最近更新 更多