Search code examples
angularjsangularjs-scope

Can't change value of $scope after get request


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);

Solution

  • 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;
            }
        });
    }