2

I want to use $timeout inside my custom AngularJS directive, but it's not working. My last implementation looks as following:

var App = angular.module('App', []);

App.controller('Controller', function($scope){
    $scope.test = true;
    $scope.toggle = function(){ $scope.test = !$scope.test;};
});

App.directive('showTemporary', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr){
                scope.$watch(attr.showTemporary, function(value){
                element.css('display', value ? '' : 'none');
            });
            $timeout(element.css('display', 'none'), attr.hideDelay);
        }
    }
}]);

And markup:

<div ng-app='App'>
    <div ng-controller='Controller'>
        <button ng-click='toggle()'>toggle</button>
        <div show-temporary='test' hide-delay="5000"> visible</div>
    </div>
</div>
0

3 Answers 3

4

You need to pass function to $timeout try:

$timeout(function () {
 element.css('display', 'none')
}, attr.hideDelay);

Also you should observe attributes, not watch.

attr.$observe('showTemporary', function(value){
                element.css('display', value ? '' : 'none');
            });

Your html was also broken:

<div show-temporary="{{test}}" hide-delay="5000"> visible</div>
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, you helped me very much, now element disapears aster delay, but only once, next task for me is to make delay work with on every click, I'll be very grateful, if you help me, here is the working fiddle: link
@snowfinch27 here you go, just remove condition in your $observe jsfiddle.net/dtjfojt1/1 and remember to use $observe, not $watch
thank you very much, I'm pretty new to AngularJS, sorry for dumb mistakes
2

Look carefully at the $timeout docs. The first parameter is FUNCTION, so you probably want it to be like this:

$timeout(function(){
    element.css('display', 'none')
}, attr.hideDelay);

Comments

0

I'm not sure what are you trying to accomplish here but this is how you should use $timeout

$timeout([fn], [delay], [invokeApply], [Pass]);

$timeout(function() {element.css('display', 'none')}, attr.hideDelay);

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.