我试图在单击按钮后在应用程序登陆的视图上访问$ scope上的数据,但似乎在使用$ location.path(url)进行重定向后,APP看不到$ scope中不再存在的变量。
带有按钮的表单:
<form ng-submit="getBrokenProbes()">
<table class="table table-striped">
<tr>
<th>Bmonitor</th>
<th>Select Bmonitor</th>
</tr>
<tr ng-repeat="bmonitor in bmonitors">
<td>
<span>{{bmonitor.domainName}}</span>
</td>
<td>
<button class="btn btn-primary" ng-click="getBrokenProbes(bmonitor)">Request</button>
</td>
</tr>
</table>
</form>
控制器:
app.controller('logmeinValidationCtrl', ['$scope','$http', '$location', function($scope,$http, $location){
$scope.bmonitors = {};
$scope.brokenProbes = {};
$http.get('http://localhost/getBmonitors').success(function (data) {
$scope.bmonitors = data;
console.log($scope.bmonitors);
});
$scope.getBrokenProbes = function(bmonitor) {
let url = 'http://localhost/getBrokenProbes';
$http.post(url, bmonitor).then(function (response) {
$scope.brokenProbes = response.data.hosts;
console.log($scope.brokenProbes);
$scope.showBrokenProbes();
})
};
$scope.showBrokenProbes = function () {
$location.path('/logmeinValidationResult')
}
}]);
我试图以其他视图显示数据,但$ scope.brokenProbes在logmeinValidationResult.html(我在$ location.path之后的页面)中不可用,因此它只显示一个空表。
logmeinValidationResult.html
<table class="table table-striped">
<tr>
<th>Probe name</th>
</tr>
<tr ng-repeat="probe in brokenProbes">
<td>
<span>{{probe.description}}</span>
</td>
</tr>
</table>
新页面控制器:
app.controller('logmeinValidationResultCtrl', ['$scope', function($scope){
console.log($scope.brokenProbes); //This yields undefined
}]);
答案 0 :(得分:1)
I)变量$scope.brokenProbes
属于定义在其中的控制器logmeinValidationCtrl
。
为了在另一个控制器中使用它,您应该传递它-广播。
OR
II)另一个(更好的)解决方案是,当用户重定向到logmeinValidationResult
时,您可以调用API,获取数据并分配给$scope.brokenProbes
变量。 / p>
在这种情况下, 您的旧控制器应如下所示:
app.controller('logmeinValidationCtrl', ['$scope','$http', '$location', function($scope,$http, $location){
$scope.bmonitors = {};
$http.get('http://localhost/getBmonitors').success(function (data) {
$scope.bmonitors = data;
console.log($scope.bmonitors);
});
$scope.getBrokenProbes = function(bmonitor) {
$location.path('/logmeinValidationResult/' + bmonitor); // Pass bmonitor to the result here so you can call the api with that parameter later on
};
}]);
这是您的新页面控制器的外观:
app.controller('logmeinValidationResultCtrl', ['$scope','$http', '$routeParams', function($scope,$http, $routeParams){
$scope.brokenProbes = [];
let url = 'http://localhost/getBrokenProbes';
let bmonitor = $routeParams.bmonitor; // Get passed bmonitor value from the route params
$http.post(url, bmonitor).then(function (response) {
$scope.brokenProbes = response.data.hosts;
console.log($scope.brokenProbes);
})
}]);
别忘了将路由参数bmonitor
注册到$ routeProvider或您使用的任何内容...