2

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

<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;
    }
}

这将做的是如果它有文本则显示注释,否则隐藏它。

我想知道的是,有没有办法ng-show从 HTML 中删除,并从控制器中动态添加它?

例如,您可以尝试将其设为 中的第一行NoteCtrl,但它不起作用:

$($element).attr('ng-show', 'hasText()');
4

3 回答 3

3

为了更接近角度行为,我建议使用 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

于 2014-07-16T10:03:43.500 回答
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>

小提琴

于 2013-01-22T02:12:13.527 回答
1

ngShow 所做的只是将 CSSdisplay属性可变地设置为“none”。因此,最简单的做法就是复制该功能:

$scope.$watch( 'text.length', function hideWhenEmpty(length){
  element.css('display', length > 0 ? '' : 'none');
});
于 2013-01-21T06:49:13.530 回答