簡體   English   中英

如何在angular.js指令中使用調用元素的文本?

[英]How to use the invoking element's text in an angular.js directive?

我正在使用angular.js指令創建可重復使用的自定義按鈕。 這是我的第一個指令,因此我一直在仔細閱讀文檔,但是我閱讀的大多數內容都假設指令代碼將對控制器模型中的數據進行操作。 但是在這種情況下,我想提供按鈕文本作為元素文本,如下所示:

<div data-custom-button>Click Me</div>

到目前為止,我能找到的最接近的方法是在div中添加一個text屬性。 我通過在指令scope.text設置為'@'來完成此操作。

<div data-custom-button data-text="Click It">Click Me</div>

因此,自定義按鈕html可以正常工作,但是按鈕文本為“ Click It”,但我希望它為“ Click Me”。 原因是該應用程序將通過i18n支持多種界面語言,該語言會填充所選語言文件中的元素文本。

所以這就是我調用指令的方式:

<div data-custom-button data-text="Click It"
     data-i18n="common:controls.login">Click Me</div>

還有customButton.js中的指令代碼:

app.directive("customButton", function() {
    return {
        replace: true,
        restrict: 'A',
        scope: {
            text: '@'
        },
        templateUrl: "customButton.html"
    };
});

還有customButton.html文件:

<div class="customButtonWrapper">
    <!-- custom html removed for clarity -->
    <div class="customButtonText">{{text}}</div>
    <!-- custom html removed for clarity -->
</div>

有沒有辦法引用調用元素的文本?

這就是ng-transclude派上用場的地方

將customButton.html更改為:

<div class="customButtonWrapper">
    <!-- custom html removed for clarity -->
    <div class="customButtonText" ng-transclude></div>
    <!-- custom html removed for clarity -->
</div>

並指示:

app.directive("customButton", function() {
    return {
        replace: true,
        transclude: true,
        restrict: 'A',
        templateUrl: "customButton.html"
    };
});

示例: jsFiddle

您可以在指令中使用鏈接功能來實現它。 基本上,鏈接函數從div讀取文本值,並將其分配給隔離的范圍變量“ text”。

app.directive("customButton", function() {
return {
      replace: true,
      restrict: 'A',
      scope: {
          text: '@'
      },
      templateUrl: "customButton.html",
      link: function(scope,element,attr){
          $scope.text = element.text();
       }
   };
});

只需使用transclude:

 app = angular.module('a',[]); app.directive('customButton', function(){ return { scope: { }, transclude: true, template: '<button class="amazing">Yo! <ng-transclude></ng-transclude></button>', restrict: 'AE' }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script> <body ng-app="a"> <div custom-button="some">Super Text</div> </body> 

暫無
暫無

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

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