我有一个指令 ( see plunk ) 用 display:none
包装一个 DIV 并在一秒钟后显示它的内容。我试图让它与 element.show() 和 $(element).show() (包括 jQuery)一起显示,但它从未奏效。超时有效,这段代码有什么问题?
这是 HTML:
<hideme>
Show this after one second
</hideme>
这是javascript:
angular.module("app", []);
function MyCtrl($scope) {}
angular.module("app").directive('hideme', function($timeout) {
return {
restrict: 'E',
template: '<div style="display: none !important"></div>',
link: function(scope, element, attrs) {
$timeout(function() {
element.show();
}, 1000);
}
};
});
最佳答案
元素已显示,问题是它不包含任何可显示的内容。此外,要具有显示功能,您需要添加 jQuery 依赖项并将其应用到正确的 div。
angular.module("app", []);
function MyCtrl($scope) {}
angular.module("app").directive('hideme', function($timeout) {
return {
restrict: 'E',
transclude: true,
template: '<div style="display: none;"><div ng-transclude></div></div>',
link: function(scope, element, attrs) {
$timeout(function() {
element.find("div:hidden").show();
}, 1000)
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<hideme>
Show me after one second.
</hideme>
</div>
就是说。我会这样做:
angular.module("app", []).directive('hideme', function($timeout) {
return {
restrict: 'E',
transclude: true,
scope: true,
template: '<div ng-show="show"><div ng-transclude></div></div>',
link: function(scope, element, attrs) {
scope.show = false;
$timeout(function() {
scope.show = true;
}, 1000)
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<hideme>
Show me after one second.
</hideme>
</div>
关于javascript - AngularJS:指令中的 element.show() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240776/