momo
momo

Reputation: 3474

Passing parameters to AngularJS controller methods

This is probably a very basic question but I can't find the answer. I just started learning AngularJs and I am trying to do a simple page with a controller where you can enter a text in an input and make a HTTP GET request. So far I have the following:

In the HTML

<body ng-app="starter" ng-controller="searchController as searchController">

<ion-pane>
  <ion-header-bar class="bar-stable">
    <h1 class="title">Ionic Blank Starter</h1>
  </ion-header-bar>
  <ion-content>
    <input type="text" ng-model="searchController.searchString" required />
    <button class="btn" ng-click="searchController.search()">Search</button>
  </ion-content>
</ion-pane>

In the controller

angular.module('starter', [])
  .controller('searchController', function() {
    this.searchURL = 'http://www.myapifilms.com/imdb?title=%thetitle%&format=JSON';
    this.searchString = '';

    this.search = function searchMovie() {
        url = this.searchURL.replace('%thetitle%', this.searchString);
        console.log("URL: " + url);
        this.searchRequest($http, url);
    };

    this.searchRequest = function ($http, url) {
        $http.get(url).success(function(data) {
            console.log("Success: " + data);
        })
    };
});

The line this.searchRequest($http, url); is obviously wrong because I have no reference to $http, which will be injected by AngularJs later.

So my question is how do I mix AngularJs services like $http with my own passed parameters? Maybe I am not structuring this properly and would love to hear comments on that. My goal is just to get input text and make a HTTP request with it.

Upvotes: 1

Views: 763

Answers (1)

Phuong Nguyen
Phuong Nguyen

Reputation: 3080

you should inject service (angular or your custom service) in controller declaration instead of passing it in the method

angular.module('starter', [])
    .controller('searchController', ["$http", function($http) {
        ...
    }]);

Upvotes: 2

Related Questions