0

I am looking for a possible solution to the below, I have an array that has an assigned watcher. My issue is changing the $scope after receiving a response from a http get request. $scope is always undefined, I need to change the value there in real time. Any suggestions would be greatly appreciated!

$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);
jmckie
  • 241
  • 4
  • 11
  • use $apply to with $scope – Yash Shukla Apr 21 '17 at 11:37
  • can u update what response you are getting from get method? –  Apr 21 '17 at 11:38
  • probably unrelated, but definitely important: [`.success` is deprecated, and has been removed from angular.js](http://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6) – Claies Apr 21 '17 at 11:42

1 Answers1

1

Actually what is undefined is the user tag at [i]. Because of the function scope of the variable, the i will be equal to the length of the array before any response from server arrives.

You could wrap the server call in a function that would accept the index or the actual tag as an argument. Like checkTag(tag) in which you make the call.

Example code:

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;
        }
    });
} 
kvetis
  • 6,682
  • 1
  • 28
  • 48