在不使用作用域的情况下,我应该如何引用控制器函数中的服务

How should I reference services in my controller functions without using scope?

本文关键字:引用 控制器 服务 函数 何引用 作用域 情况下 我应该      更新时间:2023-09-26

在阅读了几篇关于避免范围汤和参考谷歌建筑控制器指南的文章后,我留下了一个紧迫的问题。我应该如何参考我注射的控制器内的依赖关系?

到目前为止,我的方法是将服务放在我的对象上,但我对此并不满意,因为现在我的服务暴露在外部世界(模板标记)。在不直接引用$scope的情况下构建控制器,并使我注入的依赖项可用于控制器但不公开的正确方法是什么。

正如你在下面看到的,我的工作是把$http放在"this"上,然后在我的原型中引用它功能。由于上述原因,这不是我的理想选择。

http://plnkr.co/edit/Tn6Jkk06Zdu92uTM0UdU?p=preview

DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.3.0-rc2" src="https://code.angularjs.org/1.3.0-rc.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="textController as txtCtrl">
<h1>{{txtCtrl.greeting}}</h1>
<button ng-click="txtCtrl.getData()">Get Names</button>
<hr>
{{txtCtrl.names | json}}
<script>
  var textController = function($http){
    this.greeting="Hello World";
    this.$http = $http;
  }
  textController.prototype.alert = function(){
    alert(this.greeting);
  }
  /*retrieve test data from //filltext.com*/
  textController.prototype.getData = function(){
    var that = this;
    this.$http({
      method: 'GET', 
      url: 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}'
    })
    .success(function(data){
      that.names=data;
    })
    .error();
  }
  angular.module("app",[])
  .controller("textController",textController);
  angular.bootstrap(document,["app"]);
</script>

一种方法是使用IIFE创建一个闭包变量,并在控制器外部保留对http service的引用,然后在控制器中使用它。

  (function(){
      var _$http; //<-- Here a private  variable
     ......
      /*retrieve test data from //filltext.com*/
      textController.prototype.getData = function(){
        var that = this;
       _$http({ //<-- Use it
          method: 'GET', 
          url: 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}' })...
         //...
      }
      angular.module("app").controller("textController",textController);
 })();

Plnkr

或者向构造函数中添加一个属性,而不是其实例。

(function(){
    var textController = function($http){
        this.greeting="Hello World";
        textController._$http = $http; //<-- Here set it
      }
      //....
      /*retrieve test data from //filltext.com*/
      textController.prototype.getData = function(){
        var that = this;
        textController._$http({ //<-- Use it
          method: 'GET', 
          url: 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}'})...
         //...
      }
     //...
     angular.module("app").controller("textController",textController);
})();

Plnkr

以下是如何显式注释依赖项(除非您在缩小时使用ng注释)

 angular.module("app").controller("textController",['$http', 'blah', textController]);

 textController.$inject = ['$http', 'blah'];

然而,我只想把进行ajax调用和任何数据映射到服务的责任留给:-

示例:-

  angular.module("app").service('UserService', ['$http', function($http){
       this.getUsers = function(searchObj){ //Get the input and set your url
        return $http({
          method: 'GET', 
          url: 'http://www.filltext.com/?rows=10',
          params: searchObj  //<-- Pass params
        });
       }
   }]);

只需在控制器中注入userService。

 var textController = function(userSvc){
    this.greeting="Hello World";
    this.userSvc = userSvc;
  }
....
  /*retrieve test data from //filltext.com*/
  textController.prototype.getData = function(){
    var that = this;
     //Call service with argument
    this.userSvc.getUsers({firstName:$scope.fn, lastName:$scope.ln}).success(function(data){
      that.names=data;
    })...;
  }
 ....
  angular.module("app").controller("textController",['UserService', textController]);

Plnk3

我想你可能想得太多了。如果getData()需要从我们的(视图)html访问,那么它应该附加到作用域。

在您的用例中,我会使用注入器手册在闭包中保留对$http的引用。

 var $http = angular.injector(['ng']).get('$http');

这是一个更新的plunk。通过这种方式,您可以将私人物品保存在控制器中。

编辑:刚刚注意到这与@PSL解决方案非常相似。对不起,我没有注意到他的第一个解决方案。然而,我带来了手动注射器,所以如果你同意的话,我会保留这个答案!EDITEDIT:更新了plunker,使其更易于测试。