1

我想以动态方式在以下自定义元素中添加 ngshow ... 怎么做?

<toggler on-enable="main.enable()" on-disable="main.disable()">
  <div style="width:100px;height:100px;background-color:#2fa">
    <on>On state</on>
    <off>Off state</off>
  </div>
</toggler>

cf.directive('toggler', function () {
    return {
        restrict: 'AE',
        scope: {
            state: true,
            onEnable: '&',
            onDisable: '&'
        },
        compile: function (elem, attrs) {
            var onElem = elem.find('on');
            var offElem = elem.find('off');
            // WANT TO DO THIS
            // onElem.ngShow = 'state';
            // offElem.ngShow = '!state';
        }
    };
});
4

1 回答 1

3

你做错了。不要忘记 AngularJS 中的一条经验法则:避免非强制的 DOM 操作。

我猜这<on>也是<off>自定义指令,因为您不能简单地添加没有任何定义行为的标签。那么,为什么不将ngShow属性直接放在这个指令中呢?然后,指令的控制器(参见文档)将处理<on>/<off>和之间的通信<toggler>

myApp.directive('toggler', function () {
    return {
        restrict: 'AE',
        scope: {
            state: '=',
        },
        controller : [
            '$scope',
            function ($scope) {
                this.isOn = function () {
                    return $scope.state;
                };
            },
        ],
    };
});

myApp.directive('on', function () {
    return {
        restrict: 'AE',
        require: '^toggler',
        template: '<div ng-show="isOn()" ng-transclude />',
        replace: true,
        scope: true,
        transclude: true,
        link : function ($scope, element, attributes, togglerController) {
            $scope.isOn = togglerController.isOn;
        },
    };
});

myApp.directive('off', function () {
    return {
        restrict: 'AE',
        require: '^toggler',
        template: '<div ng-hide="isOn()" ng-transclude />',
        replace: true,
        scope: true,
        transclude: true,
        link : function ($scope, element, attributes, togglerController) {
            $scope.isOn = togglerController.isOn;
        },
    };
});

Fiddle

这样,您将能够简单地对您的切换器进行单元测试,并在需要时扩展其行为。

于 2013-09-29T11:32:38.987 回答