我有一个控制器,它返回搜索结果的JSON主题,我使用ng-repeat列出它们。我使用带有ng-click事件的按钮,该事件绑定到该特定对象的ID。
<div ng-controller="Gid"><button ng-click="getGid(val['gid'])">Test</button></div>
该div位于执行ng-repeat的较大控制器中。不确定是否会有所作为,但我怀疑会有所不同。
然后在“ Gid”控制器中,我有“ getGid()”函数,该函数将id作为参数。
.controller('Gid', function($scope, $http, $location){
$scope.getGid = function(id){
$http({
url: "http://127.0.0.1:5000/places/search_places",
method: "POST",
data: null
}).then(function(response){
// currently I'm just sending null to test this so I know the
// response comes back bad
}).catch(function(response){
$scope.gid = id;
console.log($scope.gid); // I can see the correct id in console
$location.path('/view1')
})
}
})
在此之后,我认为一切都会好起来的。我可以在控制台中看到确实显示了正确的ID。但是,当路径更改为view1时
<div ng-controller="Gid">
1 - {{ gid }}
</div>
gid变量保持为空。我尝试将其设置为null以从控制器顶部开始,但这没有什么区别。我尝试了没有HTTP调用的情况,这没有什么区别。但是无论如何我都需要该函数的调用才能正常工作。
那有什么呢?当我可以清楚地看到控制台中的变量已更新时,为什么变量未在视图侧更新。
最佳答案
$scope.$apply(function () {
$scope.gid = id;
});
关于javascript - AngularJS变量不会在 View 内更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48121566/