gpt4 book ai didi

javascript - 从嵌入的内容调用指令方法

转载 作者:行者123 更新时间:2023-11-30 06:29:38 24 4
gpt4 key购买 nike

我正在尝试从转译的内容中访问指令中的方法。我的 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");
}
}
}
})

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

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

这是当前代码的 Plunker:Plunker

最佳答案

我认为你不能那样做。来自Angular docs :

(...) The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope.

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

关于javascript - 从嵌入的内容调用指令方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com