[英]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.