作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有几个这样的元素:
<note ng-show="hasText()">
{{text}}
</note>
我有这样的指令:
directive('note', function() {
return {
restrict: 'E',
controller: 'NoteCtrl'
}
})
还有这样的 Controller :
function NoteCtrl($scope, $element) {
$scope.text = "Hello, world!";
$scope.hasText = function() {
return $scope.text.length > 0;
}
}
这将做的是显示注释是否有文本,否则隐藏它。
我想知道的是,有没有办法从 HTML 中删除 ng-show
,然后从 Controller 中动态添加它?
例如,您可以尝试将其设为 NoteCtrl
中的第一行,但它不起作用:
$($element).attr('ng-show', 'hasText()');
最佳答案
为了更接近 Angular 行为,我建议使用 ng-hide css 类。
从标记示例开始:
myApp.directive('note', function() {
return {
restrict: 'E',
controller: function($scope) {
$scope.text = "Hello, world!";
$scope.clearText = function() {
$scope.text = '';
}
},
link: function($scope, $element) {
$scope.$watch('text.length', function(len){
if (len <= 0) {
$element.addClass("ng-hide");
} else {
$element.removeClass("ng-hide");
}
});
}
}
})
这样,如果定义了自定义隐藏类,它也将适用于此。
(参见 https://docs.angularjs.org/api/ng/directive/ngHide)
关于angularjs - 如何从 Controller 中添加 ng-show 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433410/
我是一名优秀的程序员,十分优秀!