我有一个指令,可以创建一个允许用户执行搜索的 UI。该指令包装的内容将嵌入并成为每个单独搜索结果的模板。像这样的事情:
<search>
<div class="someStyle" ng-click="selectResult(result)">{{result.Name}}</div>
</search>
我希望 ng-click 在 Controller 的作用域上调用 selectResult 函数,但让 result
对象来自指令。如何通过指令中的隔离范围来实现此目的?
最佳答案
您可以构建自己的搜索嵌入指令,而不是使用 ng-transclude,该指令可用于将结果放入嵌入范围。例如,您的搜索指令可能看起来像这样,带有 ng-repeat 和您想要嵌入内容的 search-transclude 指令:
.directive("search", function (SearchResults) {
return {
restrict: "AE",
transclude: true,
scope: {},
template: '<div ng-repeat="result in results">Search Relevance:' +
'{{result.relevance}}' +
//the most important part search-transclude that receives the current
//result of ng-repeat
'<div search-transclude result="result"></div></div>',
link: function (scope, elem, attrs) {
//get search results
scope.results = SearchResults.results;
}
}
})
构建搜索嵌入指令如下:
.directive("searchTransclude", function () {
return {
restrict: "A",
link: function (scope, elem, attrs, ctrl, $transclude) {
//create a new scope that inherits from the parent of the
//search directive ($parent.$parent) so that result can be used with other
//items within that scope (e.g. selectResult)
var newScope = scope.$parent.$parent.$new();
//put result from isolate to be available to transcluded content
newScope.result = scope.$eval(attrs.result);
$transclude(newScope, function (clone) {
elem.append(clone);
});
}
}
})
嵌入的内容现在将能够看到 selectResult 函数(如果它存在于创建搜索指令的范围内)。示例here .
关于javascript - AngularJS : How to pass an object from the directive to transcluded template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279123/