简体   繁体   中英

Can't access function in Angular.js service

I am trying to create and use a new service in AngularJS, however, I get the following error -

Error message ProjectService.one is not a function

The Javascript -

 var app = angular.module('app', ['ngRoute']); app.service('ProjectService', function () { this.one = function one() { console.log('test service'); }; }); app.controller('ProjectsController', ['$scope', function (ProjectService, Test) { ProjectService.one(); }]); 

There is something wrong in your controller declaration. Your ProjectService parameter matches the $scope service. Do this instead;

app.controller('ProjectsController', ['$scope', 'ProjectService', 'Test', function ($scope, ProjectService, Test) {
    ProjectService.one();
}]);

The service-parameters must match the array of services (same number and order)

You've to inject the ProjectService and other required dependent modules as mentioned below:

app.controller('ProjectsController', ['$scope','ProjectService','Test', function ($scope,ProjectService, Test) {
  ProjectService.one();
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM