gpt4 book ai didi

javascript - 将参数传递给 AngularJS Controller 方法

转载 作者:行者123 更新时间:2023-11-30 17:15:39 24 4
gpt4 key购买 nike

这可能是一个非常基本的问题,但我找不到答案。我刚开始学习 AngularJs,我正在尝试使用 Controller 做一个简单的页面,您可以在其中输入文本并发出 HTTP GET 请求。到目前为止,我有以下内容:

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

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

this.searchRequest($http, url); 行显然是错误的,因为我没有引用 $http,稍后将由 AngularJs 注入(inject)。

所以我的问题是如何将 $http 等 AngularJs 服务与我自己传递的参数混合使用?也许我没有正确构建它,很想听听对此的评论。我的目标只是获取输入文本并使用它发出 HTTP 请求。

最佳答案

你应该在 Controller 声明中注入(inject)服务(angular 或你的自定义服务)而不是在方法中传递它

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

关于javascript - 将参数传递给 AngularJS Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com