Search code examples
angularjshttpangularjs-scope

Angularjs - user input in controller


I want to use a user input value in to controller. for example i want to take a URL and send a HTTP GET request. I have tried the following format , unfortunatly it does not work.

<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl' , function($scope, $http){
$http.get("{{url}}")
.success(function(response){
$scope.data=response.data;
});
});
</script>

Solution

  • Here is the url retrieved from a user's input

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    
      $scope.callAPI = function() {
        console.log($scope.url);
        $http.get($scope.url)
          .success(function(response) {
            $scope.result = response.data;
          });
      };
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
      Enter url :
      <input type="text" ng-model="url" />
      <input type="submit" ng-click="callAPI()" />
      
      <div ng-bind="result"></div>
    </div>

    Note : This will show an error if you entered a wrong url