snowfinch27 snowfinch27 - 6 months ago 24
Javascript Question

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>


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>