这是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 会同时触发(正如我们所料)。