我应该如何引用我的控制器功能的服务,而无需使用范围是什么? [英] How should I reference services in my controller functions without using scope?

查看:195
本文介绍了我应该如何引用我的控制器功能的服务,而无需使用范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取多个<经过href=\"http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html\"相对=nofollow>文章的范围,避免汤和引用的的HTTPS://google-styleguide.google$c$c.com/svn/trunk/angularjs-google-style.html #controllers相对=nofollow>谷歌指南楼宇控制器我已经离开了一个亟待解决的问题。我应该如何引用我的注入
我的控制器内的依赖呢?

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?

我的做法迄今为止是把我的对象上的服务,但我不是,作为现在我的服务接触到外面的世界(模板标记)正是开心。
什么是建立一个没有直接引用$范围控制器,并有我提供给控制器,但没有公开露注入依赖正确的做法。

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上的本,然后在我的原型的引用它
功能。不是我的上述理由理想的选择。

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=$p$ PVIEW

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

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

Plnkr

下面是你如何可以明确地标注你的依赖(除非你使用 NG-注释,以利用它,而微小)

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

Plnk3

这篇关于我应该如何引用我的控制器功能的服务,而无需使用范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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