【发布时间】:2019-01-05 14:38:39
【问题描述】:
我正在尝试访问 $scope 上的数据不再存在于 $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
}]);
【问题讨论】:
-
嗯,是的,它是未定义的,因为您从未定义它。您定义的变量在不同控制器的范围内。每个控制器都有自己的作用域(这就是它被称为作用域的原因)。看来您的发布请求实际上应该是 GET。所以从第二个控制器发出请求,而不是从第一个控制器发出请求。
-
@JBNizet 所说的。此外,您可以将 GET 请求移至服务并在整个应用程序中从那里获取您的价值:docs.angularjs.org/guide/services。否则,您可以使用 ui-router 之类的东西将状态传递给不同的控制器。 ui-router.github.io/ng1/docs/latest/modules/state.html
标签: angularjs