如何在angularjs中的控制器 - 服务 - 控制器之间传递数据

时间:2017-05-10 13:03:08

标签: angularjs

我正在尝试将来自controller1的id绑定到myservice函数之一。但是我得到以下错误

  

TypeError:_this.dashboardService.chartid不是函数

请找到我的代码段

Service1.js

var Service1 = function (
        $http) {
        this.$http = $http;
};
Service1.prototype.chartid = function (id) {
        return id;
};

appmodule.service('dashboardService', DashboardService);

controller1.js

 Controller1.prototype.Chart = function (data) {
    _this.service1.chartid(data.key);
};

2 个答案:

答案 0 :(得分:0)

您无法以更经典的方式在控制器中注入服务:

var controller1=angular.module('controllermodule',[]);


controller1.controller('{name of the controller}',function({service to inject}){}

答案 1 :(得分:0)

可以在其对象上调用Javascript原型函数。当您添加原型时,您正在定义其对象上可用的函数的类。

e.g。

var Service = function() {};

Service.prototype.callMePlease = function() {
   console.log('ok Calling now');
   return 'Just called';
};

console.log('callMePlease is undefined on Service or is it ? Service.callMePlease='+Service.callMePlease);

var serviceInstance = new Service();

console.log('callMePlease is NOT undefined on serviceInstance or is it ? serviceInstance .callMePlease='+serviceInstance.callMePlease);

var didYouCall = serviceInstance.callMePlease();

console.log('didYouCall='+didYouCall);

鉴于此,您实际上需要在您的情况下使用service1的实例。

最好按照official angularjs DI documentation按照Angular注入模型,以允许AngularJS为您创建实例。

但是你可以使用编程方法(不建议)。在你的情况下

 Controller1.prototype.Chart = function (data) {
    var myService1 = $injector.get('service1');
    myService1.chartid(data.key);
};