【问题标题】:styling checkbox with angular directive带有角度指令的样式复选框
【发布时间】:2014-06-20 17:50:37
【问题描述】:

我正在尝试使用 angular 指令设置输入 type='checkbox' 的样式,而我的 HTML 布局看起来像这样

<div class="checkbox"><input type="checkbox" ng-model="checked1" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked2" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked3" /></div>

到目前为止,我的指令如下所示:

myApp.directive('checkbox', function($parse) {
    return {
        restrict: "C",
        compile: function(elem, attr) {
            var model = $parse(attr.ngModel);

            return function(scope, elem, attr) {
                var toggleValue = function() {
                    scope.$apply(function(scope) {
                        model.assign(scope, !model(scope));
                    });
                };

                var updateComponent = function(value) {
                    if(value == true)
                        elem.addClass('checkbox-active');
                    else
                        elem.removeClass('checkbox-active');
                };

                elem.bind('click', toggleValue);

                scope.$watch(model, updateComponent);
            };
        }
    }
});

这个指令的问题是它不是从 div 内的输入中搜索 ng-model,所以如果我有这样的布局,它会起作用

<div class="checkbox" ng-model="checked1"><input type="checkbox" /></div>

我可以在指令的编译中改变一些东西,让它从输入而不是从 div 中读取 ng-model 吗?

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    你不需要像那样直接读取 ng-model 属性,ngModel 通过 ngModelCtrl 暴露一个 api。你的指令可以做到这一点

    require: "ngModel",
    

    然后在链接函数中,ngModelController就可用了

    link: function(scope, elem, attrs, ngModelCtrl) {
    

    在链接功能中,您可以检查模型的状态并相应地添加/删除类。您也可以只使用 ngClass,甚至不使用自定义指令。

    ngModelController 的文档在这里:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

    至于为什么它被应用于 div 而不是复选框?您在 div 上有 class="checkbox" 。这就是激活您的指令的原因。将 class="checkbox" 移至输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-02
      • 2018-03-07
      • 2016-01-15
      • 2016-03-07
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多