我有一个项目,我们在其中使用了很多 Angular ui-select 指令。 ui-select 的用法是标准化的,我们使用它的各个点之间的唯一区别是 ui-select-choice 模板和用于获取结果的服务。我正在尝试编写一个包装 ui-select 的 Picker 指令。我遇到的问题是嵌入 ui-select-choice 模板。
这是我写的指令。
registerDirective("picker", ["$injector", ($injector): IDirective => {
return {
restrict: "E",
templateUrl: "/Scripts/App/Views/Picker.html",
transclude: true,
scope: { model: "=model", sourceName: "=sourceName" },
link: ($scope: interfaces.IPickerScope, $: JQuery, attrs: ng.IAttributes) => {
var service = <services.IPickerService>$injector.get($scope.sourceName + "Service");
$scope.fetchResults = (filter: string) => {
service.pickerSearch(filter).then((response: any[]) => {
$scope.results = response;
});
};
}
};
}]);
指令 View :
<ui-select ng-model="$parent.model" reset-search-input="false">
<ui-select-match placeholder="Enter Item Name"><span ng-bind-html="$select.selected.name"></span></ui-select-match>
<ui-select-choices repeat="item in results"
refresh="fetchResults($select.search)"
refresh-delay="1000">
<div ng-transclude>
</div>
</ui-select-choices>
这是该指令的示例用法:
<picker source-name="'plu'" model="selectedItem">
<span ng-bind-html="item.formattedName | highlight: $select.search"></span>
<small ng-show="item.used"><em>(already in use)</em></small>
</picker>
我仍在学习 angular 的进出,这是我的第一个嵌入实验。我注意到选择器正在使用嵌入模板,但没有设置任何范围变量。我很确定这是一个与 transclude 和 scope 行为方式相关的范围问题。我已经研究过使用 compile 和 transclude 函数,但似乎无法完全达到我需要的地方。
最佳答案
删除指令的 scope
规范。如果您确实指定了它,该指令将创建它自己的范围,并且被嵌入的部分将绑定(bind)到 外部范围 。如果您没有为指令指定作用域,则指令和被嵌入部分都将绑定(bind)到外部作用域,从而允许您正在寻找的行为。
关于angularjs - 带有 ui-select 和 transclude 的 Angular 指令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30536605/