HTML 文件是这样的:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>HTTP Request</title>
<script src="angularjs"></script>
<script src="appjs"></script>
</head>
<body>
<div ng-controller="myCtrl1">
First Name: <input type="text" ng-model="fname" required>
Last Name: <input type="text" ng-model="lname" required>
<button ng-click="search()">Send HTTP Request</button>
<p>Searching for : {{fname}} {{lname}}</p>
<p>Response Status: </p>
<p>{{status}}</p>
<p>Data: {{data}}</p><br>
<p>Total number of results : {{data.numResults}}</p>
</div>
</body>
</html>
我写了一个控制器:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl1', ['$rootScope', '$http', function($rootScope, $http) {
$rootScope.fname = "";
$rootScope.lname="";
$rootScope.search = function() {
var search_url = "/search?fname=" + $rootScope.fname + "&lname=" + $rootScope.lname;
alert (search_url);
// alert("/search?fname=" + $scope.fname + "&lname=" + $scope.lname);
$http({method:'GET', url:search_url})
.success(function(data, status, headers, config) {
$rootScope.status = status;
$rootScope.data = data;
$rootScope.headers = headers;
$rootScope.config = config;
});
};
}]);
但它在警报框中显示 url 为:/search?fname=&lname= 但是当我在任何地方使用 $scope 而不是 $rootScope 时,它工作正常(警报窗口正确显示 url /search?fname=john&lname=player)。需要帮助以详细了解 $rootScope。谢谢。