簡體   English   中英

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

[英]Use $timeout inside custom AngularJS directive

我想在自定義AngularJS指令中使用$ timeout,但是它不起作用。 我的最后一個實現如下所示:

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

和標記:

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

您需要將函數傳遞給$ timeout試試:

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

另外,您應該觀察屬性,而不是觀察。

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

您的html也已損壞:

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

仔細查看$ timeout文檔 第一個參數是FUNCTION,因此您可能希望它像這樣:

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

我不確定您要在這里完成什么,但這就是您應該使用$ 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