Frenck
Frenck

Reputation: 6534

Pass ng-data to scope

I'm trying to create a live search function with AngularJS. I got a input field:

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

it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the 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
  });
});

Upvotes: 1

Views: 164

Answers (3)

Justin John
Justin John

Reputation: 9616

Inside the angular controller use a watch expression.

$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 */ });
  }
});

Upvotes: 1

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

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

Upvotes: 0

MiTa
MiTa

Reputation: 1340

You can use watch as @Justin John proposed, or can use ng-change when using ng-change your controller should look something like this

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

and your html

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

Upvotes: 0

Related Questions