在angular中,我如何将输入变量检索到javascript控制器上?

how do I retrieve an input variable onto a javascript controller in angular?

本文关键字:检索 变量 javascript 控制器 输入 angular      更新时间:2023-09-26

我有一个搜索输入字段,我正试图将该输入发送到我想使用的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
});