0

I would like to instantly update {{card.likeCount}} (on the HTML page) when user click on like anchor tag.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>

            <li>
                <i class="fa fa-eye">
                </i>
                {{card.likeCount}}
            </li>
            <li>
                <a  href="#" ng-click="likingCard(card.id)" name>
                    Like
                    </i>
                </a>
            </li>

This is how I currently do it, I add this code to cardCtrl, I'm not sure if I'm using the right approach:

    $scope.likingCard = function(id) {
    $http.post('/card/like/', {
        id: id
    }).then(function onSuccess(result, status, headers, config) {

        setTimeout(function() {
            $scope.likeCount = parseInt(result.data.likeCount);
            console.log($scope.likeCount);
            $scope.$digest();
        }, 1000);

    }).catch(function onError(err) {
        console.log('Error:', err);
    })
}

2 Answers 2

1

I don't understand why, when you say "instantly update", you have inserted a deliberate 1 second delay after receiving the response before you update the model.

If you don't want the delay, just update the model:

$scope.likingCard = function(id) {
    $http.post('/card/like/', {
        id: id
    }).then(function (result) {
            $scope.likeCount = parseInt(result.data.likeCount);
            console.log($scope.likeCount);
    }).catch(function (err) {
        console.log('Error:', err);
    })
}

If you do want the delay then don't use setTimeout, use $timeout instead and you won't need the explicit call to $digest.

$scope.likingCard = function(id) {
$http.post('/card/like/', {
    id: id
}).then(function (result) {

    $timeout(function() {
        $scope.likeCount = parseInt(result.data.likeCount);
        console.log($scope.likeCount);
    }, 1000);

}).catch(function (err) {
    console.log('Error:', err);
})

}

Sign up to request clarification or add additional context in comments.

Comments

0

make use of ng-cloak directive

<body ng-cloak>
<!-- all your angular stuff here -->
</body>

you can also use ng-cloak directly on <html> tag

for more details check documentation here

https://docs.angularjs.org/api/ng/directive/ngCloak

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.