簡體   English   中英

在Angularjs中的另一個指令模板中使用一個指令

[英]Use one directive inside another directive template in Angularjs

我是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事件根本不起作用。 有什么建議可以解決這個問題嗎? 謝謝

檢查元素,你會看到

在此輸入圖像描述

basetext模板在輸入標記內,無效。

你需要在basetext指令上放置replace: true, property,然后它將替換子指令模板的元素。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM