简体   繁体   English

在自定义AngularJS指令中使用$ timeout

[英]Use $timeout inside custom AngularJS directive

I want to use $timeout inside my custom AngularJS directive, but it's not working. 我想在自定义AngularJS指令中使用$ timeout,但是它不起作用。 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试试:

$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: 您的html也已损坏:

<div show-temporary="{{test}}" hide-delay="5000"> visible</div>

Look carefully at the $timeout docs . 仔细查看$ timeout文档 The first parameter is FUNCTION, so you probably want it to be like this: 第一个参数是FUNCTION,因此您可能希望它像这样:

$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的方式

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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