0

下面是我的视图,从视图中我使用附加到控制器中特定 URL 的 id 来检索相应的 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>

我的控制器是:

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

在上面的控制器中,我试图从视图中访问 id 并附加 URL,但$scope.id给出了未定义的值。

4

1 回答 1

0

变量url必须在函数内部初始化getBook为,

由于url变量在首次加载应用程序期间被初始化,因此它不需要更新的用户输入......

$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);
    });
}
于 2016-03-20T16:23:12.563 回答