我想在我的自定义 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>
关于javascript - 在自定义 AngularJS 指令中使用 $timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644622/