[英]AngularJs calling service function from controller
我在AngularJs中有一些应用程序,但遇到了问题。 我需要从控制器中的服务调用函数。
我的服务:
var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
function print () {
console.log('smth');
}
}
我的控制器:
var Controller = function ($scope, $state, OffersService, commonFunction, dataService, alert, blockUI) {
function printSmth () {
dataService.print();
}
}
从html中的ng-init调用了函数printSmth,并且出现异常,说dataService.print不是函数。
有人知道这样做的正确方法吗? 我无法将其更改为.service,必须以这种方式完成。
尝试如下。
var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
this.print = function () {
console.log('smth');
};
}
要么
var DataService = ['$http', '$q', '$window', 'alert', function ($http, $q, $window, alert) {
function print() {
console.log('smth');
};
return {
print: print
};
}
达到目标的最佳方法是:
服务:
/* recommended */
// dataservice factory
angular
.module('app.core')
.factory('dataservice', dataservice);
dataservice.$inject = ['$http', '$q', '$window', 'alert'];
function dataservice($http, $q, $window, alert) {
return {
print : print
};
function print () {
console.log('smth');
}
}
控制器:
/* recommended */
// controller calling the dataservice factory
angular
.module('app.avengers')
.controller('YourController', YourController);
YourController.$inject = ['$scope', '$state', 'OffersService', 'commonFunction', 'dataservice', 'alert', 'blockUI'];
function YourController($scope, $state, OffersService, commonFunction, dataservice, alert, blockUI) {
$scope.printSmth = function printSmth() {
dataService.print();
};
}
我建议您开始阅读style guides for AngularJS
一些style guides for AngularJS
。 将来,您将使您的生活和开发团队更加高效。
var Controller = function ($scope, $state, OffersService, commonFunction, dataService, alert, blockUI) {
将dataService
更改为DataService
----------------更新--------------------
除非有$scope
函数,否则无法在视图中访问在控制器中定义的函数。
因此,将控制器中的打印功能设置为
$scope.printSmth = function () {
dataService.print();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.