[英]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. 我刚开始学习AngularJs,我试图用控制器做一个简单的页面,您可以在输入中输入文本并发出HTTP GET请求。 So far I have the following: 到目前为止,我有以下内容:
In the HTML 在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);
这行this.searchRequest($http, url);
is obviously wrong because I have no reference to $http, which will be injected by AngularJs later. 显然是错误的,因为我没有引用$ http,稍后将由AngularJs注入。
So my question is how do I mix AngularJs services like $http with my own passed parameters? 所以我的问题是如何将像$ http这样的AngularJs服务与自己传递的参数混合使用? 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. 我的目标只是获取输入文本并使用它发出HTTP请求。
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) {
...
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.