angularjs - Angular 形式 : setting a $dirty property on a custom directive

标签 angularjs angularjs-directive

我们有一个指令(比方说复选按钮)创建一个具有某些特定功能的样式化复选框。

我在指令中需要 ng-form,所以我可以在指令中使用 formCtrl,我成功地将 form 设置为 $dirty 或 $valid。 我的问题 是如何将指令创建的特定元素设置为 $valid 或 $dirty 并且通常表现为 Angular 形式元素。只是做 element.$valid = false 并不像 fromCtrl.addControl(element) 那样工作所以我被卡住了。我应该强调这个指令在 ng-repeat 循环中使用,所以我可以在它上面设置一个“名称”,因为 ng-repeat 可以编程设置一个名称(必须是一个字符串)

这是(简化的)模板:

<div class="check-button ">
    <div c" ng-class="{ 'active': value != undefined ? btnState == value : btnState }">
        <i class="icon-ok"></i>
    </div>
    <div class="pull-left btn-label" ng-transclude></div>
</div>

这是代码:

angular.module('our.directives').directive('checkButton', [function() {
    return {
        restrict: 'A',
        require:'?^form', //may be used outside a form
        templateUrl: '/tempalte/path/tpocheckbutton.html',
        scope: {
            btnState: '=ngModel',
            value: '=radioBtn'
        },
        replace: true,
        transclude: true,
        link: function($scope, $element, $attrs, formCtrl) {
            if(formCtrl){

                formCtrl.$addControl($element)//doesn't work
            }

            $scope.$watch(function() {
                return $scope.btnState;
            }, function(newValue) {
                $scope.btnState = newValue;
            });

            var _onElementClick = function() {
                if($scope.value != undefined) {
                    $scope.btnState = $scope.value;
                } else {
                    $scope.btnState = !$scope.btnState;
                }
                if(formCtrl){
//                    $element.$dirty = true;//doesn't work
                    formCtrl.$setDirty(); //does set the form as dirty - but not the field
                }

            };

            $element.find('.button, .btn-label').on('click', _onElementClick);
        }
    };
}]);

我们使用的是最新的 Angular 版本 (1.2.10)

最佳答案

您基本上需要 formngModel 作为 form.$addControl 需要一个 ngModelController

关于angularjs - Angular 形式 : setting a $dirty property on a custom directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444013/

相关文章:

javascript - Angular - 如何从 promise 中访问对象

angularjs - Chrome 开发者工具中未定义 Angular

angularjs - 如何使用ng-if和table根据条件显示td

javascript - 在指令中编译后获取元素的内容

javascript - AngularJS - 使用 angularjs 拖放列表库时没有在 html 页面中获取任何内容

angularjs - 升级到 1.3 后 Controller 未在 Typescript 应用程序中定义

angularjs - 如何绑定(bind)指令范围的深层子属性?

javascript - 为什么 $watch 中的监听函数没有被触发?

javascript - AngularJS 指令在隔离范围内的双向绑定(bind)未反射(reflect)在父范围中

javascript - ng-messages 仅在触摸时显示错误并在初始显示错误时进行转换