2017-04-13 96 views
0

我在AngularJs中有一些应用程序,并且遇到了问题。我需要从控制器中的服务调用一个函数。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(); 
    } 
} 

功能printSmth是从HTML NG-INIT调用,我得到异常说dataService.print不是一个函数。

有没有人知道正确的方法来做到这一点?我不能改变它.service它必须这样做。

回答

1

尝试像下面..

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 
     }; 
} 
+0

和它的作品!谢谢 – egzaell

+0

欢迎@egzaell –

0
var Controller = function ($scope, $state, OffersService, commonFunction, dataService, alert, blockUI) { 

变化dataServiceDataService

---------------- UPDATE ------------------ -

您在控制器中定义的功能无法在视图中访问,除非其功能为$scope

因此,请打印功能在您的控制器是

$scope.printSmth = function() { 
    dataService.print(); 
} 
+0

没了,我得到了同样的异常,以及有关那种在控制器我有工作访问瓦尔在DataService的 – egzaell

+0

思维看一看@egzaell –

+0

我更新了答案@egzaell –

1

的最佳途径,你想要完成的任务会是这样的:

服务:

/* 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(); 
    }; 
} 

我建议你开始阅读一些​​3210。您将使您的生活和您的开发团队在未来更高效。

+1

这是一个很好的例子,使用一些良好的做法编写。请参考这个。 –

+0

这真的很好,但不是在我的情况 – egzaell

相关问题