简体   繁体   中英

Use $timeout inside custom AngularJS directive

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>

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM