2016-11-05 42 views
2

我有一個搜索輸入字段,我試圖將該輸入發送給我想要使用的JavaScript變量。這是角如何檢索一個輸入變量到一個JavaScript控制器的角度?

輸入

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

我位於從HTML文件不同的地方的JavaScript文件。

非常感謝提前。

+0

任何具體的原因,爲什麼你想訪問的角度應用程序外的JavaScript的變量?或者它是在角度的應用程序,但從一個不同的控制器或東西 – Sreekanth

+0

我想執行一個搜索github的存儲庫,我可以做一個硬編碼的變量。但現在我試圖做一個搜索,並努力獲得變量的JavaScript文件才能使用它。它假設是一個簡單的搜索,但我失去了一些東西。 – kuhle

+0

您只需在控制器中使用$ scope.searchText來訪問該值。 – Sreekanth

回答

1

你可以做這樣的事情。

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>

+0

非常感謝。有用! :) – kuhle

1

你可以實現你的邏輯在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="[email protected]" 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>

0

你的代碼是正確的。要麼,如果你手動添加一個searchText屬性$scope或者你只是依靠ng-model="searchText"(這也自動增加一個屬性$scope),您的控制器將使用$scope.searchText接入綁定的<input>值:

angular.module('searchkingApp') 
    .controller('MainCtrl', function($scope){ 
     var searchedItem = $scope.searchText; 
    }); 

現在,你可以做一個當用戶執行某些事件的操作(例如,一個click事件)或觀看$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 
}); 
相關問題