AngularJS出现TypeError: serviceName.functionName()非函数,求实现取消按钮返回功能
Hey there! Let's break this down into two parts: getting your cancel button's redirect functionality working as intended, and fixing that frustrating TypeError: serviceName.functionName() is not a function error you're hitting.
First, let's refine your code to make the redirect work properly. Here's the complete, corrected version:
View Code
<div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div>
Controller Code
Make sure your controller is registered with your AngularJS module and dependencies are correctly injected:
angular.module('yourAppModule') .controller('goodCtrl', function($scope, $log, goodService) { $scope.cancel = function() { $log.debug("goodCtrl - cancel"); goodService.cancel(); // No need to pass $scope unless your service explicitly requires it }; });
Service Code
Your service needs to expose its methods and be properly registered. Also, fill in your target state for the redirect:
angular.module('yourAppModule') .service('goodService', function($log, $state) { var methods = { cancel: function() { $log.debug("goodService - cancel"); // Replace 'targetState' with your actual state (e.g., 'home' or 'goods.list') $state.go('targetState'); } }; return methods; // Critical step to make service methods accessible! });
Note: I removed passing $scope to the service's cancel method since it doesn't seem necessary here. If you do need to use $scope in the service later, you can add it back, but it's best practice to avoid this unless absolutely required.
This error almost always means Angular can't locate the method you're trying to call on your service. Here are the key fixes to check:
- Service Registration: Double-check that
goodServiceis properly registered with your module using.service()or.factory(). If you skip this step, the controller can't inject the service at all. - Expose Public Methods: In your service, you must return the
methodsobject (or individual functions) to make them public. Forgettingreturn methods;will leave your service with no accessible methods. - Spelling Consistency: Verify you're using the exact same service name (
goodService) when registering it and injecting it into the controller. Typos (likeGoodServiceorgoodservice) are an extremely common culprit. - Module Alignment: Ensure your controller and service belong to the same Angular module, or that the module containing the service is imported into the module with the controller.
- UI-Router Dependency: Confirm you've included the
ui-routermodule in your app's main dependencies (since you're using$state). Missing this will break$state.go()and could cause indirect issues with your service.
Run through these checks, and that TypeError should vanish while your cancel button redirect works as expected!
内容的提问来源于stack exchange,提问作者zzangs33

