Oyzuu
Oyzuu

Reputation: 371

Function inside setTimeout doesn't modify $scope variables / CSS properties

I'm battling with setTimeout(), unable to even grasp what the problem could be. I first thought that it was a scope problem but can't fix it.

I'd like to delay the hiding/unhiding of a DIV to let my CSS transition on opacity kick in but when I click the alert_button to fade then hide the alert, it only fades and I'm left with an invisible div. Delayed $scope.alert_token doesn't switch to 'true' and the opacity of my alert stuck on 1.

app.js :

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
    $scope.alert_token = true // hide if true
    $scope.alert_message = ""
    $scope.p_name = ""

    $scope.isInArray = function(arr, item) {
        // IF ITEM IS ALREADY IN ARRAY
        if (arr.indexOf(item) > -1) {
            $scope.alert_token = !$scope.alert_token
            $scope.alert_message = "Entry already exists"
            setTimeout(function() {
                document.getElementById("alert").style.opacity = "1"
            }, 305)
        }
        else ...
    }

    $scope.submit = function(listType) {
        if (listType == "player") {
            $scope.isInArray(p_list, $scope.p_name)
            $scope.p_name = ""
        }
        else ...
    }

    $scope.closeAlert = function() {
        document.getElementById("alert").style.opacity = "0"
        setTimeout(function() {
            $scope.alert_token = !$scope.alert_token
        }, 305)
    }

Upvotes: 0

Views: 115

Answers (1)

Zee
Zee

Reputation: 8488

Anything happening outside angular's knowledge is not updated to the DOM. In you case its setTimeout. Instead use $timeout.

......
.controller('myCtrl', function($scope, $timeout) {...
                                       ^^^^^^^^
//Other code
....
   $scope.closeAlert = function() {
        document.getElementById("alert").style.opacity = "0"
        $timeout(function() {//$timeout
            $scope.alert_token = !$scope.alert_token
        }, 305)
    }

Also since you are using angularJS, to update CSS properties I would recommend you to use ngClass and ngStyle

Upvotes: 1

Related Questions