离子/角度JS控制器无法识别功能

时间:2017-02-01 19:53:23

标签: angularjs ionic-framework service controller

所以,我是角度和离子的新手。

我的Serives.js文件如下所示:

angular.module('app.services', [])

.factory('serviceName', function () {
    var z = 2;

    return {
        doStuff: function (x) {
            return x * z;
        },
        doMoreStuff: function (y) {
            return y * z;
        }
    }
})

现在我想在我的一个控制器中使用函数doStuff:

.controller('weineCtrl', ['$scope', '$stateParams',function ($scope, $stateParams, serviceName) {
var test = serviceName.doStuff(3); }])

每次我运行页面时都会收到错误:

TypeError: Cannot read property 'doStuff' of undefined
at new <anonymous> (controllers.js:21)
at Object.instantiate (ionic.bundle.js:18015)
at $controller (ionic.bundle.js:23417)
at Object.self.appendViewElement (ionic.bundle.js:59908)
at Object.render (ionic.bundle.js:57901)
at Object.init (ionic.bundle.js:57821)
at Object.self.render (ionic.bundle.js:59767)
at Object.self.register (ionic.bundle.js:59725)
at updateView (ionic.bundle.js:65400)
at ionic.bundle.js:65377

什么不对???

1 个答案:

答案 0 :(得分:4)

您需要在控制器中包含serviceName作为另一个依赖项,如下所示:

.controller('weineCtrl', ['$scope', '$stateParams', 'serviceName', function ($scope, $stateParams, serviceName) {
var test = serviceName.doStuff(3); }])