获取请求后无法更改 $scope 的值
Can't change value of $scope after get request
我正在寻找以下问题的可能解决方案,我有一个数组,该数组已分配了观察者。我的问题是在收到来自 http get 请求的响应后更改 $scope。 $scope 始终未定义,我需要实时更改那里的值。任何建议将不胜感激!
$scope.$watch('user.tags', function (newVal, oldVal) {to invalid until the
$scope.tags_valid = true;
// Loop through array and validate length
for (var i = 0; i < $scope.user.tags.length; i++) {
if ($scope.user.tags[i].data.length != 24) {
$scope.tags_valid = false;
return;
}
// Check if already exists
$http.get("api/registration/TagExists", { params: { Tag_Id: $scope.user.tags[i].data } }).success(function (response) {
if (response == "true") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = true;
}
});
}
}, true);
实际上未定义的是 [i]
处的用户标签。
由于变量的函数范围,i
将等于服务器响应到达之前数组的长度。
您可以将服务器调用包装在一个接受索引或实际标记作为参数的函数中。就像您在其中拨打电话的 checkTag(tag)
。
示例代码:
function checkTag(tag) {
$http.get("api/registration/TagExists", { params: { Tag_Id: tag.data } }).success(function (response) {
if (response == "true") {
tag.is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
tag.is_valid = true;
}
});
}
我正在寻找以下问题的可能解决方案,我有一个数组,该数组已分配了观察者。我的问题是在收到来自 http get 请求的响应后更改 $scope。 $scope 始终未定义,我需要实时更改那里的值。任何建议将不胜感激!
$scope.$watch('user.tags', function (newVal, oldVal) {to invalid until the
$scope.tags_valid = true;
// Loop through array and validate length
for (var i = 0; i < $scope.user.tags.length; i++) {
if ($scope.user.tags[i].data.length != 24) {
$scope.tags_valid = false;
return;
}
// Check if already exists
$http.get("api/registration/TagExists", { params: { Tag_Id: $scope.user.tags[i].data } }).success(function (response) {
if (response == "true") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
// $scope is always undefined here
$scope.user.tags[i].is_valid = true;
}
});
}
}, true);
实际上未定义的是 [i]
处的用户标签。
由于变量的函数范围,i
将等于服务器响应到达之前数组的长度。
您可以将服务器调用包装在一个接受索引或实际标记作为参数的函数中。就像您在其中拨打电话的 checkTag(tag)
。
示例代码:
function checkTag(tag) {
$http.get("api/registration/TagExists", { params: { Tag_Id: tag.data } }).success(function (response) {
if (response == "true") {
tag.is_valid = false;
$scope.tags_valid = false;
} else if (response == "false") {
tag.is_valid = true;
}
});
}