0

これが私の状況を例示するjsfiddle.netです。

app=angular.module("app",[]);

app.directive("submitForm",function(){
    return{
        scope:{},
        restrict: 'A',
        controller:function($scope, $element){
            $scope.submitted=false;

            this.submit=function(){
                $scope.submitted=true;
            };
            this.getSubmit=function(){
                return $scope.submitted;
            };
            this.submitOn=function(){
                return $scope.$broadcast("submitOn");
            };
        },
        link: function(scope, element, attrs,ctrl){
            element.find("button").on("click",function(){
                scope.submitted=true;
                ctrl.submitOn();
            });
        }
    }
})
.directive('errorRender',function(){
    return{
        restrict: 'A',
        //scope: {},
        require:['ngModel','^submitForm'],
        controller: function($scope, $element){
            $scope.$broadcast("requireErrorEnable");

            $scope.$broadcast("requireErrorDisable");

            $scope.$broadcast("maxlengthErrorEnable");

            $scope.$broadcast("maxlengthErrorDisable");
        },
        compile: function compile(tElement, tAttrs) {

            return function postLink(scope, element, attrs, ctrl) {
                modelCtrl=ctrl[0];
                formCtrl=ctrl[1];

                scope.$on("submitOn",function(){
                    alert("submitOn!!!");
                });

                scope.$on("requireErrorEnable",function(){
                    element.attr("placeholder","error");
                });

                scope.$on("requireErrorDisable",function(){
                    element.attr("placeholder","");
                });

                scope.$watch(function(scope){
                        return ctrl[0].$error.required;
                    },
                    function(newValue, oldValue, scope){
                        if(ctrl[0].$error.required){
                            if((ctrl[0].$dirty && !ctrl[0].$viewValue)){
                                scope.$emit("requireErrorEnable");
                            }
                        }else{
                            scope.$emit("requireErrorDisable");
                        }
                    });
            }
        }
    }
});

ディレクティブerrorRenderを分離スコープで使用すると、この場合、ディレクティブのコントローラーの関数submitFormを起動できません。それ以外の場合は、すべてのディレクティブerrorRenderが同時に発生します (予想どおり)。

4

1 に答える 1

0

ディレクティブはrequire、正しく指定したプロパティを介してコントローラーを共有できます。これは、ディレクティブに関するAngularのドキュメントが、ディレクティブのコントローラーへのアクセスについて述べていることです(強調を追加):

" require- 別のディレクティブを要求し、そのコントローラーをリンク関数の 4 番目の引数として挿入します。requireは、渡すディレクティブの文字列名 (または文字列の配列) を取ります。配列が使用されている場合、注入された引数は対応する順序の配列である必要があります。そのようなディレクティブが見つからない場合、またはディレクティブにコントローラがない場合、エラーが発生します

私見、あなたのケースに適用すると、これは、コントローラーが挿入されるリンク関数が、親ではなく、子ディレクティブにあることを意味します

于 2013-09-24T09:46:20.343 に答える