AngularJS指令中$mdSelect无法使用,报错$mdSelect.hide不是函数
Fixing "$mdSelect.hide is not a function" Error in Your AngularJS Directive
Let's break down what's going wrong here and fix it step by step:
The Root Causes
You've got a couple of parameter shadowing issues that are blocking you from accessing the actual $mdSelect service:
- Link function parameter misplacement: The 4th argument in the
linkfunction is reserved for a directive controller (if you defined one), not the injected$mdSelectservice. Adding$mdSelecthere overwrites the injected service withundefinedsince there's no controller for this directive. - Event callback parameter shadowing: Your
$mdMenuCloseevent handler declares$mdSelectas a parameter, which again overwrites the injected service. The actual parameters for this event are(event, menuElement), so your extra$mdSelectparameter just ends up asundefined.
Corrected Directive Code
Here's the fixed version of your directive:
namespace Xxx{ angular.module('Xxx') .directive('mdCloseSelect', ['$mdSelect', ($mdSelect) => { return { link (scope, element, attrs) { // Removed the extra $mdSelect parameter here scope.$on('$mdMenuClose', (ev, menuElement) => { // Removed the extra $mdSelect parameter here // Optional safety check to avoid errors if hide() isn't available if (typeof $mdSelect.hide === 'function') { $mdSelect.hide(); } }); } }; }]); }
Explanation
- By removing the unnecessary
$mdSelectparameters from both thelinkfunction and event callback, you can now access the actual$mdSelectservice you injected at the directive level. - The optional safety check ensures you only call
hide()if the method exists, preventing unexpected errors if$mdSelectis in an unexpected state.
This should resolve the "$mdSelect.hide is not a function" error, as you'll now be calling the method on the proper $mdSelect service instance.
内容的提问来源于stack exchange,提问作者Peter Boomsma
相关产品推荐
相关产品推荐

