0

I am trying to call a $http Get service on button click in angular js. But I am not getting the data to show in results... My code snippet is as follows:-

<button ng-controller="myCtrl6" ng-click="search()">Click</button>
<p ng-controller="myCtrl6">
  {{results}}
  {{fail}}
</p>
var app = angular.module("myApp", []);
app.controller('myCtrl6', ['$scope', '$http', function ($scope, $http) {
  $scope.results = "";
  $scope.fail = "f";
  $scope.search = function() {
    $http.get('welcome.html', {}, function(response) {
      $scope.results = response.data; 
    }, function (failure) { 
      console.log("failed :(", failure); 
    });
  }
}]);

welcome.html

Hello World
Gerald Gonzales
  • 533
  • 2
  • 6
  • 20
Sunil Keshari
  • 99
  • 1
  • 2
  • 11

2 Answers2

1

This is the proper use of $http

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // in your case 
    $scope.results = response.data; 
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

or

$http.get('/someUrl', config).then(successCallback, errorCallback);

Better make a service for this :

app.factory('ServiceName', function() {
  return {
     search: search
  };

  function search () {
    return $http.get('/someUrl', config);
  }
});

in controller

var app = angular.module("myApp", []);
app.controller('myCtrl6', ['$scope', 'ServiceName', function ($scope, serviceName) {
  $scope.search = function() {
    serviceName.search().then(function(response) {
      $scope.results = response.data; 
    });
  }
}]);

Edited

Yordan Nikolov
  • 2,598
  • 13
  • 16
0

Wrap your button and p tag inside div(main container), by doing this you can access your controllers scope only inside that main container not outside of that.

<div ng-controller="myCtrl6">
        <p >{{results}}
        {{fail}}
        </p>
        <button ng-click="search()">Fetch Data</button>
</div>

And in script.js file write

$scope.search = function () {                    
          $http.get('welcome.html')
          .success(function(response) {
            $scope.results = response;
          })
          .error(function(error) {
            console.log("error is : " + JSON.stringify(error))
          })
    }
kuns
  • 44
  • 3