我应该如何在不使用范围的情况下在我的控制器函数中引用服务? [英] How should I reference services in my controller functions without using scope?

查看:22
本文介绍了我应该如何在不使用范围的情况下在我的控制器函数中引用服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看了几篇关于避免范围汤和引用的文章用于构建控制器的 Google 指南 我有一个紧迫的问题.我应该如何参考我的注射我的控制器中的依赖项?

After reading several articles on avoiding scope soup and referencing the Google Guidelines for building controllers I have been left with one burning question. How should I reference my injected dependencies within my controller?

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

My approach thus far is to put the services on my object but I'm not exactly happy with that as now my services are exposed to the outside world (the template markup). What is the correct approach to build a controller without directly referencing $scope, and have my injected dependencies available to the controller but not exposed publicly.

正如您在下面看到的,我的解决方法是将 $http 放在this"上,然后在我的原型中引用它职能.由于上述原因,这不是我的理想选择.

As you can see below my work around is to put $http on 'this' and then reference it in my prototyped functions. Not my ideal choice for the aforementioned reasons.

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 服务 的引用保留在控制器之外,并使用它在控制器中.

One way you could do is to create a closure variable using IIFE and keep reference of http service outside the controller, and use it in the controller.

  (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

或者向构造函数添加一个属性而不是它的实例.

Or add a property to the constructor instead of its instance.

(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-annotate)在缩小时取用它)

Here is how you can explicitly annotate your dependencies (unless you use ng-annotate which will take of it while minification)

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

或者

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

但是,我只负责进行 ajax 调用和任何到服务的数据映射:-

However i would just leave the responsibility of making ajax calls and any data mapping to a service:-

示例:-

  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.

And just inject userService in the controller.

 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

这篇关于我应该如何在不使用范围的情况下在我的控制器函数中引用服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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