AngularJS - 从服务调用控制器功能 [英] AngularJS - Calling a controller function from a service

查看:135
本文介绍了AngularJS - 从服务调用控制器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是那么的绿角时,我甚至不知道我已经正确地构建这个搜索。整个指令和服务用语仍扑朔迷离我一些,但是这不是我的问题。

I'm so green at Angular, I'm not even sure I've been structuring a search for this correctly. The whole directive and service terminology is still confusing me some, but that isn't my question.

我读过这个优秀的系列文章中从前到后:<一href=\"http://www.ng-newsletter.com/posts/beginner2expert-how_to_start.html\">http://www.ng-newsletter.com/posts/beginner2expert-how_to_start.html

I've read this excellent article series front to back: http://www.ng-newsletter.com/posts/beginner2expert-how_to_start.html

这就是为什么我在我的应用程序这一点。为什么我知道我的问题涉及更多的服务和控制器之间的关系。而非句法相关

Which is why I am at this point in my application. And why I know my question relates more to the relationship between services and controllers. Rather than syntax-related.

因此​​,这里的应用程序的概述:

So here is an overview of the app:

我有一个控制器。这熄灭,并得到了一堆使用AJAX调用到PHP文件中的用户非农数据,并使用它自己的$范围显示在屏幕上。

I have one controller. This goes off and gets a bunch of farm data for the user using an AJAX call to a PHP file, and displays it on screen using it's own $scope.

var masterApp = angular.module('masterApp', ['myFilters','commonControls']);

masterApp.controller('MasterCtrl', ['$scope','$http', '$filter', 'commonFarmSelector', 
    function($scope, $http, $filter, commonFarmSelector){

        ...

        $scope.masterCtrl.loadFarmData = function(farmId) {
            var postdata = {
               "farmId":farmId
            };

            $http.post('/service/farmproduction', postdata).success(function (data) {
                // Do stuff with the $scope using data
            }
        }

        $scope.masterCtrl.loadFarms();
}

您会看到我注射一种叫commonControls。这是我创建的用于保存将由多个控制器可重复使用的控制模块。在这种情况下,包含农场的列表,用户可以访问(也由AJAX调用获得)下拉字段

You will see I am injecting something called "commonControls". This was a module I created to hold controls that will be reused by multiple controllers. In this case, a dropdown field that contains a list of farms the user has access to (also obtained by an AJAX call):

var commonControlsApp = angular.module('commonControls', []);

commonControlsApp.controller('farmSelectorCtrl', ['$scope', '$http',function($scope, $http) {

    $scope.farmSelectorCtrl ={}

    // Change entire farm view when a different farm is selected
    $scope.farmSelectorCtrl.switchUserFarm = function() {
        var farmId = $scope.farmSelectorCtrl.selectedUserFarm;
        $scope.masterCtrl.loadFarms(farmId); // !!! Direct link to masterCtrl
    };

    // Get a list of the user's farms
    $http.post('/service/userfarms').success(function (data) {
        $scope.farmSelectorCtrl.userFarms = data.getFarmsPerUserResult.farmIds;
    });

}]);

这工作正常。但正如你所看到的,farmSelector直接关系到masterCtrl。这loadFarmData函数的行为是特定于该控制器。换句话说,它只会做了适用于该网页的东西。

This works fine. But as you can see, the farmSelector is directly linked to masterCtrl. And the behavior of that loadFarmData function is specific to that controller. In other words, it will only do things that apply to that page.

问题是,这farmSelector将在其他页面中使用。和改变事件的precise行为将每一页不同。所以我努力工作在哪里这种行为应该坐下。以及它如何会被称为依赖使用farmSelector控制器上。

The thing is, this farmSelector will be used on other pages. And the precise behavior of a change event will be different for each page. So I am struggling to work out where this behavior should sit. And how it would be called dependent on the controller using the farmSelector.

我在上面链接的文章表明,这farmSelector应该是一个服务,因此它可以在其他地方重复使用。但我仍然困惑着你如何给一个通用服务的特定操作时被触发事件承担。

The article I have linked above suggests this farmSelector should be in a service so it can be reused elsewhere. But I am still confused over how you could give a generic service a specific action to take when an event is triggered.

推荐答案

我极力推荐服务,并为本文提出同样的道理。它也有一个伟大的回答你的问题。

I highly recommend a service as well, for the same reason the article suggests. It also has a great answer to your problem.

你想要的东西的技术术语叫做 calback功能即可。它是precisely,具体操作时被触发的事件采取,和文章的服务节提供了如何做一个很好的例子。

The technical term for what you want is a calback function. It is, precisely, a specific action to take when an event is triggered, and the Services section of the article provides a good example of how to do this.

看看服务的文章(我已经下调的重要部件),本节

Take a look at this section of the Services article (which I've trimmed down to the important parts)

angular.module('myApp.services', [])
  .factory('githubService', ['$http', function($http) {

    var doRequest = function(username) {
      return $http({
        url: 'https://MySuperURL.com/getTheData'
      });
   }

    return {
      events: doRequest
    };

}]);

所以,我们必须得服务,名为 githubService ,它有一个方法:事件(这是真的只是为 doRequest 一个不同的名字。我不停的重命名,以便它会与文章的code匹配)

So we've got a service now, called githubService, which has one method: events (which is really just a different name for doRequest; I kept the rename so that it would match with the article's code.)

这里的幕后隐藏的是在 $ Q 的API,它有时也被称为承诺API。功能 $ HTTP 返回一个承诺的对象,这是真的只是一个为code跟踪会发生什么时,承诺做方式。例如,让我们来看看这下code(再次,从文章的版本修改):

Hidden here behind the scenes is the $q API, which is sometimes referred to as the 'promise' API. The function $http returns a 'promise' object, which is really just a way for the code to keep track of what should happen when the 'promise' is done. For example, let's look at this next code (again, modified from the article's version):

app.controller('ServiceController', ['$scope', 'githubService',
function($scope, githubService) {

  // uses the $http service to call the GitHub API
  // and returns the resulting promise
  githubService.events(newUsername)
    .success(function(data, status, headers) {
         // do magic stuff with the result
         // (which is in the data param)
         $scope.events = data.data;
    })
});

}]);

这是那里的魔力正在发生的事情。看看调用成功(),你会看到,他们实际上是通过一个函数这应该是当请求工作运行。该功能还可以访问所有的的ServiceController 由于封闭的变量,因此它允许使用 $范围和其他变量。然而,这是非常有可能通过将每一次不同的功能,它可以让多个控制器采取不同的行动来写不同成功()方法,每个控制器。当请求完成后,它会调用每个成功函数,它被赋予。

This is where the 'magic' is happening. Look at the call to success(), and you'll see that they are actually passing a function that should be run when the request works. The function still has access to all the variables in the ServiceController due to closure, so it's allowed to use $scope and other variables. However, it's very possible to write a different success() method in every controller by passing a different function each time, which lets multiple controllers take different actions. When the request finishes, it will call every success function that it was given.

您可以按照此code的例子,得到一个工作模型,但我也建议你看一看的 $ q在角,也看看这篇关于回调函数。您需要了解双方才能真正得到这是怎么回事,但好消息是,他们都用于经常在棱角分明,所以这将是值得你的时间。

You could follow this code example and get a working model, but I also suggest that you take a look at $q in angular, and also take a look at this article about callback functions. You need to understand both to really get what's going on, but the good news is that they are both used quite often in angular, so it will be worth your time.

这篇关于AngularJS - 从服务调用控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆