假设我有几个这样的元素:
<note ng-show="hasText()">
{{text}}
</note>
我有这样的指示:
directive('note', function() {
return {
restrict: 'E',
controller: 'NoteCtrl'
}
})
这样的控制器:
function NoteCtrl($scope, $element) {
$scope.text = "Hello, world!";
$scope.hasText = function() {
return $scope.text.length > 0;
}
}
这将做的是显示注释是否有文本,否则隐藏它。
我想知道的是,有没有办法从HTML中删除ng-show
,并从控制器中动态添加它?
例如,您可以尝试将此作为NoteCtrl
中的第一行,但它不起作用:
$($element).attr('ng-show', 'hasText()');
答案 0 :(得分:3)
为了更接近角度行为,我建议使用ng-hide css类 从Marks例子开始:
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)
答案 1 :(得分:1)
所有ngShow都可以将CSS display
属性可变地设置为“none”。因此,最简单的方法就是复制该功能:
$scope.$watch( 'text.length', function hideWhenEmpty(length){
element.css('display', length > 0 ? '' : 'none');
});
答案 2 :(得分:1)
结合@ Valentyn和@Josh的输入,这里只是一个指令,它只在控制器中进行数据操作,并使用链接函数进行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){
$element.css('display', len > 0 ? '' : 'none');
});
}
}
})
HTML:
<note>
{{text}}
<br><a ng-click="clearText()">clear text</a>
</note>