2015-11-02 61 views
2

我對Angularjs來說很新穎,並嘗試在另一個指令中實現一個指令。我有一個處理基本輸入事件的兒童指令basetext和處理與輸入有關的其他任務的myTextbox。我做了一個simple plunker來證明我的問題。我已經實現在Angularjs的另一個指令模板中使用一個指令

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"); 
      } 
     } 
    } 
}); 

的問題即blur事件和focus事件basetext指令根本不起作用。任何建議來解決這個問題?由於

+1

只看到生成的html。 'basetext'把'輸入'與輸入裏面的事件應用此指令 – Grundy

+0

好吧,我會嘗試。 – Rebel

回答

1

檢查元素,你會看到

模板的

enter image description here

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

+2

有趣的是,我認爲'replace'應該_replace_元素,而不是_extend_它:-) – Grundy

+0

謝謝,它的工作。 – Rebel

+1

太棒了,很高興幫助你:) –

相關問題