簡體   English   中英

AngularJs指令 - <script> inside template

[英]AngularJs Directive - <script> inside template

我有一個帶模板的指令,在這個模板中我有一個<script>標簽,使用該指令的變量。

指示:

    (function () {
      'use strict';

      angular
        .module('app.components')
        .directive('picker', Picker);

      /*@ngInject*/
      function Picker() {

        return {
          restrict: 'E',
          controller: PickerController,
          controllerAs: 'vm',
          bindToController: true,
          templateUrl: 'picker.html',
          transclude: true,
          scope:{
            inputId: '@'
          }
        };

        /*@ngInject*/
        function PickerController() {
          /*jshint validthis: true */
          var vm = this;
        }

      }
    })();

模板:

    <div>
      <div>
        id: {{vm.inputId}}
        <ng-transclude></ng-transclude>
      </div>
      <script>
        console.log({{vm.inputId}});
      </script>
    </div>

用法:

    <picker input-id="myInput"> <!-- something... --> </picker>

問題是<script>標記內的{{vm.inputId}}未被過濾,因此{{vm.inputId}}不會成為“myInput”。 一切都在<script>標記之外, id: {{vm.inputId}}變為id: myInput

是不是可以將“變量”放在腳本標記中?

實現的代碼片段

<script>
      console.log({{vm.inputId}});
</script>

可以在指令的控制器中很好地實現。 這將允許您運行javascript代碼,可以訪問您的變量。

例如,你可以這樣:

var app =  angular.module('myApp', [])

app.directive('testDirective', function(){
  return {
    restrict: 'E',
    template: '<p>Click in the text box</p>'+
              '<textarea id="my-area"></textarea>'+
              '<p>Click {{num_clicks}}</p>',
    controller: function($scope, $log){
      $scope.num_clicks = 0;
      $("#my-area").click(function(){
        incr();
      });
      function incr(){
        $scope.num_clicks = $scope.num_clicks + 1;
        $scope.$digest();
        $log.log("A click",   $scope.num_clicks);
      }

    }
  };
});

我希望這有幫助

我不建議在模板中使用<script>標簽。

如果要在加載視圖時記錄inputId的值,則可以使用ngInit指令。

<div ng-init="log(vm.inputId)">
    id: {{vm.inputId}}
    <ng-transclude></ng-transclude>
</div>

並將日志功能添加到控制器中的范圍:

app.controller('myController', function($scope, $log) {
    $scope.log = function (message) {
        $log.log(message)
    };
});

好吧, jQlite不支持模板中的腳本標記 jQuery可以,所以如果你需要這個功能,建議包括jQuery。

進一步,

即使您在模板中使用<script>標記,其中的代碼也會 angular的上下文之外執行。 因此,您將無法訪問模板文件中<script>標記內控制器范圍內的任何變量。 這基本上意味着,做類似的事情

  <script>
    console.log({{vm.inputId}});
  </script>

是不可能的,因為更新的vm,也沒有inputId可用,你會得到一個錯誤聲稱Unexpected token {{

同樣,你可以在控制器中編寫相同的代碼。 那么為什么要復雜化

如果您仍打算在模板中使用<script> ,那么這里有一個plunkr

只需在您的索引中包含庫腳本和其余腳本(角度等)。

您仍然可以將datepicker包裝在指令中 - 使用指令的link函數。 如果jQuery在您的項目中,您將可以訪問鏈接函數的“element”參數上的所有jquery函數。

angular.module('myModule').directive('datepicker', function () {
  return {
    link: function (scope, elem, attrs) {
      elem.jqdatepicker({ /* options */ });
    }
  };
});

暫無
暫無

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

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