我正在页面上多次使用指令,例如:
<div data-escape-amp-curation-multi-value-selector
data-binding-path="model"
data-search-key="journeys"
data-current-selection-model="model.journeys">
</div>
<div data-escape-amp-curation-multi-value-selector
data-binding-path="model"
data-search-key="targets"
data-current-selection-model="model.targets">
</div>
我的指令看起来像这样
var directive : ng.IDirective = {
restrict : 'A',
template : '<select multiple="multiple" data-options="sources/>',
compile() {
return {
pre(scope : any, element : any, attrs : any) {
scope.readonly = attrs.readonly === 'true';
},
post(scope : any, element : any, attrs : any) {
var binder = $parse(attrs.currentSelectionModel),
valueDropDown = element.find('select.value-dropdown'),
kendoMultiSelect = valueDropDown.data('kendoMultiSelect'),
defer = $q.defer();
/**
* The method to do search.
* @type {void}
*/
scope.doSearch = () = > {
scope.showSpinner = true;
scope.$evalAsync(() = > {
if (!cache) {
metadataService.getMetadata(attrs.searchKey).then(
result = > {
cache = result;
scope.sources = result;
defer.resolve();
},
error = > {
defer.reject(error);
});
} else {
scope.sources = cache;
defer.resolve();
}
defer.promise.then(() = > {
kendoMultiSelect.setDataSource(scope.sources);
scope.showSpinner = false;
kendoMultiSelect.value(binder(scope));
});
});
};
kendoMultiSelect.bind('change', () = > {
binder.bind(scope, kendoMultiSelect.value());
});
/**
* Set cache to null on location change
*/
scope.$on(LOCATION_CHANGE_START, () = > {
cache = null;
});
scope.$watch(() = > scope.$eval(attrs.currentSelectionModel), () = > {
if (!scope.sources) {
if (angular.isDefined(cache) && cache !== null) {
$timeout(() = > {
scope.sources = cache;
kendoMultiSelect.setDataSource(scope.sources);
kendoMultiSelect.value(binder(scope));
});
} else {
scope.doSearch();
}
} else {
kendoMultiSelect.setDataSource(scope.sources);
kendoMultiSelect.value(binder(scope));
}
});
}
}
}
}
当这段代码渲染时,它调用后端服务根据搜索关键字填充数据源,但是Bot实例的scope.sources得到了相同的值。 它获取了最后一次搜索服务调用的值。 我在这里缺少什么? 谢谢。
$cacheFactory
。你可以将它注入到你的指令中,并创建一个自定义命名的缓存。只要您对缓存键进行合理的命名,就不必担心全局声明的问题。 - Josh