在angular中,我如何将输入变量检索到javascript控制器上?
how do I retrieve an input variable onto a javascript controller in angular?
我有一个搜索输入字段,我正试图将该输入发送到我想使用的JavaScript变量。这是在Angular
中输入<input ng-model="searchText" placeholder="Search">
controller.js
angular.module('searchkingApp')
.controller('MainCtrl', function($scope){
//which code can i put under here?
//and end up having
var searchedItem = //the string I have searched for..
JavaScript文件位于与HTML文件不同的位置。
你可以这样做。
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.searchText = "Hello";
$scope.search = function() {
console.log($scope.searchText);
}
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<input ng-model="searchText" />
<button ng-click="search()">Search</button>
</div>
</div>
你可以在AngularJS应用程序中实现你在Github上搜索的逻辑。
在searchOnGithub()
方法中,您可以使用$http来调用PHP脚本,传递变量$scope.searchText
的值,然后在视图中显示结果。
希望这有助于开始:
angular
.module('myApp', [])
.controller('myController', function ($scope) {
$scope.searchOnGithub = function() {
// Do your logic to perform the search on Github
console.clear();
console.log($scope.searchText);
};
});
<script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="searchText" ng-change="searchOnGithub()" placeholder="Search">
</div>
您的代码很好。如果您手动添加searchText
属性到$scope
,或者您只是依赖于ng-model="searchText"
(这也自动添加属性到$scope
),您的控制器将使用$scope.searchText
访问绑定的<input>
值:
angular.module('searchkingApp')
.controller('MainCtrl', function($scope){
var searchedItem = $scope.searchText;
});
现在,您可以在用户执行某些事件(例如,单击事件)时执行操作,或者监视$scope.searchText
以查看更改:
<input type="text" ng-click="search()">
$scope.search = function() {
// $scope.searchText will give the search terms
};
……或者:
// You would go this way if you want to implement something like
// Google Instant Search so you don't need to click anything, you perform
// searches whenever the <input> changes
$scope.$watch(function() { return $scope.searchText; }, function(newValue, oldValue) {
// newValue contains current $scope.searchText value
});
相关文章:
- 如何在JavaScript中检索变量的名称
- 如何从Mysql检索变量并在JS中的函数中使用它
- 尝试检索变量以检查表单是否有效
- Javascript 正则表达式从句子中检索变量
- 从 JavaScript 传递后无法检索变量
- 从函数中检索变量
- 从python Appengine中的Javascript函数中检索变量
- 如何在jQuery中检索变量的值
- 从 javascript 对象方法回调中检索变量
- 从javascript循环中的函数中检索变量
- 用javascript在onclick中检索变量
- 用Java解析JavaScript代码以检索变量'的名字
- 如何检索变量而不是echo
- 使用ajax加载函数检索变量
- jquery.从文本文件中获取和检索变量
- 在JavaScript函数中从SQL查询中检索变量(重写)
- 从包含 Javascript 中包含的 JSON 数据的 HTML 中检索变量
- 从HTML网站检索变量名
- 从twitter的json对象中检索变量
- 索引页检索变量从所有的帖子