0

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)
    }
1
  • 1
    You would need to use $timeout or scope.$apply() (bad practise) with setTimeout inorder for digest cycle to kick in to update DOM Commented May 29, 2015 at 19:13

1 Answer 1

1

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

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

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.