簡體   English   中英

AngularJs從控制器調用服務功能

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM