将数据传递到范围

时间:2014-09-07 15:06:28

标签: javascript json angularjs

我正在尝试使用AngularJS创建实时搜索功能。我有一个输入字段:

<input type="text" placeholder="Search" data-ng-model="title" class="search">

在那里传递范围内的搜索关键字,这样我就可以执行实时搜索(JS)并直接将结果显示给DOM

var app = angular.module("DB", []);

app.controller("Controller", function($scope, $http) {
  $scope.details = [],

  $http.defaults.headers.common["Accept"] = "application/json";
    $http.get('http://api.org/search?query=<need to pass search name here>&api_key=').

    success(function(data, status, headers, config) {

    }).
    error(function(data, status, headers, config) {
      //handle errors
  });
});

3 个答案:

答案 0 :(得分:1)

在角度控制器内部使用监视表达式。

$scope.$watch('title', function (newValue, oldValue) {
  if(newValue != oldValue) {
    $http.get('http://api.org/search?query=' + newValue + '&api_key=')
         .success(function(data, status, headers, config) { /* Your Code */ })
         .error(function(data, status, headers, config) { /* Your Code */ });
  }
});

答案 1 :(得分:0)

<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">

app.controller("Controller", function($scope, $http) {
  $scope.details = [],

  $scope.search= function() {
    var url = "http://api.org/search?query="+$scope.title+"&api_key=";
     $http.defaults.headers.common["Accept"] = "application/json";
     $http.get(url).

    success(function(data, status, headers, config) {

    }).
    error(function(data, status, headers, config) {
      //handle errors
  });
  };     
});

答案 2 :(得分:0)

你可以使用@Justin John提出的手表,或者可以使用ng-change 当使用ng-change时,您的控制器应该看起来像这样

app.controller("Controller", function($scope, $http) {

  $http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
  $scope.details = [];

  $scope.search= function() {
    $http.get("http://api.org/search?query="+$scope.title+"&api_key=")
       .success(function(data, status, headers, config) { .... })
       .error(function(data, status, headers, config) {//handle errors });
  }
});

和你的HTML

<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">