【问题标题】:Angular directive default to checkedAngular 指令默认为选中
【发布时间】:2015-07-16 19:19:16
【问题描述】:

我有一个为“开关”创建的指令(元素),它使用 input[checkbox]。

只要不选中复选框的初始状态,一切正常。但是如果我想将初始状态设置为选中(基于我的控制器值),那么它总是相反。为什么当控制器变量说应该检查时没有检查该值?

HTML

<a-switch toggle-state="vm.doSomething"></a-switch>

指令 Html

<div class="switch-container">
    <input type="checkbox" id="switch" />
    <label for="switch" class="pm-switch"></label>
</div>

Javascript 控制器

vm.doSomething = {
    state: true
};

指令

angular.module('material')
    .directive('aSwitch', [
        '$timeout', function($timeout) {
            return {
                templateUrl: 'elements/material/switch/switch.html',
                transclude: false,
                restrict: 'E',
                scope: {
                    toggleState: '=',
                },
                link: function (scope, element) {
                    element.on('click touchstart', function (event) {
                        if (event.srcElement && event.srcElement.id && event.srcElement.id === "switch") {
                            event.stopPropagation();

                            $timeout(function() {
                                scope.toggleState.state = !scope.toggleState.state;
                            });
                        }
                    });
                }
            };
        }
    ]);

我意识到为了设置泛型的选中状态

<input type="checkbox" />

我只需要添加属性“checked”,比如

<input type="checkbox" checked />

但是如果它在我的指令的 html 中,我该怎么做呢?

【问题讨论】:

  • 你可以通过&lt;input type="checkbox" id="switch" ng-model="toggleState.state"/&gt; 来解决这个问题,然后超时函数将是`$timeout(function() { scope.toggleState.state = scope.toggleState.state? scope.toggleState.state: false; });
  • 哇,使用这种方法否定了我的指令中对“链接”部分的需求,请将其添加为答案,以便我给你积分
  • 酷,我会在一个小时内完成..

标签: javascript html angularjs checkbox angularjs-directive


【解决方案1】:

当您使用其中包含scope: { toggleState: '='} 的隔离范围时,您应该将toggleState.state 直接绑定到模板内的输入框,以便链接功能代码将被删除,因为toggleState 有两种方式使用toggle-state 属性与您的控制器范围变量绑定

Directive.html

<div class="switch-container">
    <input type="checkbox" id="switch" ng-model="toggleState.state"/>
    <label for="switch" class="pm-switch"></label>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-20
    • 2017-10-02
    • 2013-09-18
    • 2013-12-27
    • 2018-07-24
    • 2018-03-07
    • 2016-08-01
    • 2018-11-29
    相关资源
    最近更新 更多