【问题标题】:AngularJS) TypeError : serviceName.functionName() is not a functionAngularJS) TypeError : serviceName.functionName() 不是函数
【发布时间】:2018-09-05 10:15:14
【问题描述】:

我想做“当取消 btn 点击时返回”功能。

这是查看代码

<div ng-controller="goodCtrl">    
<button class="btn" ng-click="cancel()">Cancel</button>
</div>

这是Js代码

1) 控制器

function goodCtrl($scope, $log, goodService)
    $scope.cancel = function(){
        $log.debug("goodCtrl - cancel");
        goodService.cancel($scope);
    };

2) 服务

function goodService($log, $state)
    var methods = {
       cancel: function($scope) {
           $log.debug("goodService - cancel");
           $state.go('goback');
       }
    }

3) 模块

angular
    .module('goodmodule')
    .controller('goodCtrl', goodCtrl)
    .service('goodService', goodService)

但我遇到了这个问题

TypeError : serviceName.functionName() 不是函数

虽然有这么多的控​​件、服务、方法这样写,但我添加的服务和控制器是不可用的。 我错过了什么?

【问题讨论】:

  • 这是字面上的错误信息吗?在您的代码中看不到任何类似的内容

标签: javascript html angularjs model-view-controller


【解决方案1】:

在 angularjs 中,要定义一个 service,您必须在 service 函数中的 this 关键字中分配属性。因为在angular js中构造函数是用来创建自定义服务的。下面的代码是你更新后的服务代码。

    function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}

【讨论】:

  • 我解决了问题!它是因为没有返回方法而发生的。谢谢!
【解决方案2】:

正如您定义的那样,service 注册方法要使用 this 公开

function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}

我也推荐你使用Dependency Annotation,这里我使用了$inject属性注解

 goodCtrl.$inject = ['$scope', '$log', 'goodService'];
 goodService.$inject = ['$log', '$state'];

【讨论】:

猜你喜欢
  • 2017-06-25
  • 1970-01-01
  • 2017-05-17
  • 2023-04-01
  • 2012-10-23
  • 2016-07-12
  • 2015-11-23
  • 2015-03-13
  • 2015-09-21
相关资源
最近更新 更多