AngularJS,使用服务调用Controller

时间:2014-08-20 22:59:30

标签: angularjs angularjs-service angularjs-controller

我是Angular的新手,我想要完成的是:从服务/工厂直接将方法调用到控制器中。

在下面的代码中,我想从valueUserController我想从服务myApi创建一个方法,并在valueController中设置值。

这是我的代码:

模块/ myApi.js

var MyApi = app.factory('MyApi', function() 
    var api = {};

    api.getCurrentValue = function() {
        // needs to access the Value controller and return the current value
    }

    api.setCurrentValue = function(value) {
        // needs to access the Value controller and set current value
    }

    api.getValueChangeHistory = function() {
        // access value controller and return all the values
    }

);

控制器/ value.js

app.controller('valueController', function($scope) {

    var value = 0;

    function getValue() {
        return value;
    }

    function setValue(inValue) {
        value = inValue;
    }

    // ......
});

控制器/ valueUser.js

app.controller('valueUserController', function($scope, myApi) {

    function doStuff() {
        var value = myApi.getValue();
        value++;
        myApi.setValue(value);
    }
});

我发现在AngularJS中这样做非常困难,我在这里找不到任何类似的帖子。

感谢您的帮助,

安德烈

1 个答案:

答案 0 :(得分:0)

尝试与服务中的特定控制器通信并不是正确的思考方式。服务需要是一个孤立的实体(通常持有一些状态),控制器才能与之交互。

考虑到这一点,您可以使用类似事件模式的内容来实现您的目标。例如,当您的服务完成某个特定流程时,您可以触发如下事件:

$rootScope.$broadcast('myEvent', { myValue: 'someValue' });

然后,系统中的任何控制器都可以监视该事件并在需要时执行特定任务。例如,在控制器内部,您可以执行以下操作:

$scope.$on('myEvent', function(event, data){
    // Do something here with your value when your service triggers the event
    console.log(data.myValue);
});
相关问题