How should I refer to services in my controller functions without using a scope?

After reading several articles on avoiding volume soup and links to Google Guidelines for building controllers, I still have one burning question. How should I refer to my dependency injection inside my controller?

So far, my approach is to host services on my site, but I'm not quite happy with this, because now my services are exposed to the outside world (template markup). What is the correct approach to creating a controller without a direct reference to the $ scope, and my nested dependencies are available to the controller, but have not been published publicly.

As you can see below, my job is to put $ http on 'this' and then reference it in a prototyped function. Not my ideal choice for the above 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>

+4
source share
3 answers

One way you can do this is to create a closure variable using IIFE and save the link http serviceoutside 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, )

 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

+2

, . getData() (view) html, .

0

, $http .

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

. , .

EDIT: Just noticed that this seems like a @PSL solution. Sorry, I did not notice his first decision. Nevertheless, I give a manual nozzle, so I keep this answer if it is good! EDITEDIT: Updated plunker to be more testable.

0
source

All Articles