gpt4 book ai didi

angularjs - 如何从 Controller 中添加 ng-show 功能?

转载 作者:行者123 更新时间:2023-12-02 22:16:02 26 4
gpt4 key购买 nike

假设我有几个这样的元素:

<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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com