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- 需要另一个指令并将其控制器作为第四个参数注入到链接函数中。require 接受要传入的指令的字符串名称(或字符串数​​组)。如果使用数组,注入的参数将是一个相应顺序的数组。如果找不到这样的指令,或者如果指令没有控制器,则会引发错误“

恕我直言,当应用于您的情况时,这意味着注入控制器的链接功能是您的子指令中的一个,而不是父指令

于 2013-09-24T09:46:20.343 回答