2014-06-18 53 views
0

我正在編寫一個<password>指令,其中將包含一個<input>後跟一個<span>(允許用戶顯示/隱藏密碼的圖標)。是否有可能讓Angular用這兩個元素替換HTML中的指令元素,並將指令元素上存在的所有屬性應用於<input>元素?我可以用兩個元素替換Angular指令嗎?

所以:

<password ng-model="myVar" ng-change="myTrigger" ng-whatever="myWhatever"></password> 

將成爲:

<span> 
    <input type="password" ng-model="myVar" ng-change="myTrigger" ng-whatever="myWhatever"/> 
    <span ng-click="togglePasswordVisibility()">show/hide</span> 
</span> 

,如果用戶添加任何其他屬性<password>讓他們施加於<input>

回答

2

你將不得不做手工的元素編譯之前:

.directive('password', function($compile) { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<span>' + 
      '<input type="password" />' + 
      '<span ng-click="togglePasswordVisibility()">show/hide</span>' + 
      '</span>'; 
     compile: function($element, $attr) { 
      return function($scope, $element, $attr) { 
       var input = $element.find('input[type=password]'), 
        attributes = $element.prop("attributes"); 
       angular.forEach(attributes, function() { 
        input.attr(this.name, this.value); 
       }); 
       $compile($input)($scope); 
      } 
     } 
    } 
}); 

還沒有測試過,但我認爲這是要走的路(可能不是最好的一個)

+0

謝謝!這正是我所期待的。如果有任何問題,我會測試它並更新它,但對我來說,這看起來沒問題。 – stackular

1

您可以使用替換指令,但我會重新命名指令或者只是添加前綴,它得到的一個問題

.directive('password', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<span>' + 
      '<input type="password" ng-model="myVar" ng-change="myTrigger" ng-whatever="myWhatever"/>' + 
      '<span ng-click="togglePasswordVisibility()">show/hide</span>' + 
     '</span>' 
    }; 
    }); 
+0

這遠不是我所問的。這是最簡單的指令。它不會選擇新的屬性,它會從使用它的範圍中調用toggleKitPasswordVisibility()。這幾乎是無用的。 – stackular

+0

@stackular然後寫一個更清晰的問題。 – Shomz

+0

@Shomz:這個建議的答案很荒謬。你可以隨心所欲地玩弄聰明的屁股,但我不明白這個問題的表達方式如何更清晰。再次閱讀問題(以問號結尾的句子)並查看接受的答案。 – stackular

相關問題