Search code examples
angularjsangularjs-scopeangular-controller

In my angularJS controller am appending the URL with a dynamic value from the view, but getting undefined value


Below is my view, from the view I am using the id which is appended to the particular URL in the controller to retrieve corresponding Book

<div ng-controller="viewBookController">
<form ng-submit="getBook()">
    Your ID:<input type="text" ng-model="id"/><br>
    <input type="submit" value="View Book"/><br>
    Book Author : {{book.author}}<br>
    Book Title : {{book.title}}<br>
</form>
</div>

and my controller is :

mainApp.controller("viewBookController", function($scope,$http) {
var resData = {};
$scope.book = {};
var url = "http://localhost:8080/webservice-1.0/rest/book/"+ $scope.id;
$scope.getBook = function(){
    $http.get(url)
    .then(function(response) {
        $scope.book = angular.fromJson(response.data);
    });
}
});

In the above controller, I am trying to access the id from the view and appending with the URL, but $scope.id is giving undefined value.


Solution

  • The variable url must be initialised inside the getBook function as,

    Since url variable gets initialised during first time app loading, it doesn't take the updated user input...

    $scope.getBook = function(){
        var url = "http://localhost:8080/webservice-1.0/rest/book/"+ $scope.id;
        $http.get(url)
        .then(function(response) {
            $scope.book = angular.fromJson(response.data);
        });
    }