2014-10-03 165 views
1

這可能是一個非常基本的問題,但我找不到答案。我剛開始學習AngularJs,我試圖用控制器做一個簡單的頁面,您可以在輸入中輸入文本併發出HTTP GET請求。到目前爲止,我有以下幾點:將參數傳遞給AngularJS控制器方法

在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> 

在控制器

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); 
     }) 
    }; 
}); 

this.searchRequest($http, url);顯然是錯誤的,因爲我沒有提到的$ HTTP,稍後將由AngularJs注入。

所以我的問題是如何混合AngularJs服務,如$ http與我自己傳遞的參數?也許我沒有正確地設計這一點,並希望聽到關於此的評論。我的目標是獲取輸入文本並用它發出HTTP請求。

回答

2

你應該在注入控制器申報服務(角或您的自定義服務),而不是通過它的方法

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

這奏效了,感謝! – momo 2014-10-03 03:53:38

相關問題