从传入的内容调用指令方法

Call directive method from transcluded content

本文关键字:调用 指令 方法      更新时间:2023-09-26

我正试图从已计算的内容访问指令中的方法。我的HTML看起来像:

<typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer">
  <ul>
    <li ng-click="select(customer)" ng-repeat="customer in customersfiltered | filter:filter | limitTo:10">
      {{customer.firstname}} {{customer.lastname}}
    </li>
  </ul>
</typeahead>

我的AngularJS指令:

directive('typeahead', function ($filter) {
    return {
      restrict: 'E',
      transclude: true,
      replace: true,
      scope: {
        model: '=',
        filteredModel: '='
      },
      template: '<div class="typeahead"><form><input type="text" autocomplete="off" class="col-lg-12" ng-model="filter"></form><div ng-transclude></div></div>', //
      controller: function($scope){
        $scope.filterArray = function(filterString){
          $scope.filteredModel=  $filter('filter')($scope.model, filterString);
        }
        $scope.clear = function(){
          $scope.filteredModel = [];
        }
        $scope.$watch('filter', function(){
          if($scope.filter) {
            $scope.filterArray($scope.filter);
          } else {
            $scope.clear();
          }
        });
      },
      link: function ($scope, $element, $attributes) {
        $scope.select = function(customer){
          console.log("dwadad");
        }
      }
    }
  })

这里的问题是,我无法从transcluded内容(列表元素)的ng-click事件访问链接函数()中的select()函数。

有人知道如何解决这个问题吗

以下是当前代码的Plunker:Plunker

我认为你做不到。来自Angular文档:

(…)transclusion的优点是链接函数接收预先绑定到正确范围的transclusion函数。在典型的设置是小部件创建一个隔离作用域,但是transclusion不是一个子项,而是隔离范围的兄弟项。这使小部件可以具有私有状态,并且要绑定到父(预隔离)范围的transclusion。

换句话说,transcluded DOM的作用域是指令作用域的兄弟,而不是子。所以你不能从那里访问它,我认为这是正确的。否则,您将无法将transcluded内容绑定到正确的范围。

您可以使用$$nextSibling:

link: function($scope) {
    $scope.$$nextSibling.select = function(customer) {
        alert('used isolated scope using $$nextSibling');
    }
},