【问题标题】:Use $timeout inside custom AngularJS directive在自定义 AngularJS 指令中使用 $timeout
【发布时间】:2016-07-28 18:56:06
【问题描述】:

我想在我的自定义 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>

【问题讨论】:

    标签: javascript angularjs angular-directive


    【解决方案1】:

    您需要将函数传递给 $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>
    

    【讨论】:

    • 谢谢,你帮了我很大的忙,现在元素消失了 aster delay,但只有一次,我的下一个任务是让延迟在每次点击时都起作用,如果你能提供帮助,我将不胜感激我,这是工作小提琴:link
    • @snowfinch27 在这里,只需删除 $observe jsfiddle.net/dtjfojt1/1 中的条件并记住使用 $observe,而不是 $watch
    • 非常感谢,我对 AngularJS 很陌生,对于愚蠢的错误感到抱歉
    【解决方案2】:

    仔细查看$timeout docs。第一个参数是 FUNCTION,所以你可能希望它是这样的:

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

    【讨论】:

      【解决方案3】:

      我不确定你想在这里完成什么,但这就是你应该如何使用 $timeout

      $timeout([fn], [delay], [invokeApply], [Pass]);
      
      $timeout(function() {element.css('display', 'none')}, attr.hideDelay);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        • 2020-10-28
        • 1970-01-01
        相关资源
        最近更新 更多