使用“需要"在指令中要求父控制器 [英] Using "require" in Directive to require a parent Controller
本文介绍了使用“需要"在指令中要求父控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试要求"一个父控制器(不是指令),但 AngularJS 返回一个异常.代码是这样的:
JS
app.controller("myController", function ($scole) {...});app.directive("myDirective", function ($q) {返回 {要求:^ myController",模板: "",链接:函数(范围、元素、属性、myCtrl){...}};});
HTML
...<div 我的指令>...</div>...
错误
<块引用>错误:[$compile:ctreq] 控制器myController",需要指令myDirective",找不到!
为什么?
也许,require
属性必须引用指令的控制器?
谢谢
解决方案
Require是在另一个指令中使用其他指令控制器,请参考下面的例子
var App = angular.module('myApp',[]);//一个指令App.directive('oneDirective',function(){返回 {限制:'E',控制器:功能($范围){$scope.myName= function(){console.log('我的名字');}}}});//两条指令App.directive('twoDirective',function(){返回 {require:'oneDirective'//使用了一个指令,链接:函数(范围,元素,属性,oneCtrl){console.log(oneCtrl.myName())}}})
I try to "require" a parent controller (not directive) but AngularJS returns an exception. The code is like this:
JS
app.controller("myController", function ($scole) {
...
});
app.directive("myDirective", function ($q) {
return {
require: "^myController",
template: "",
link: function (scope, element, attrs, myCtrl) {
...
}
};
});
HTML
<div ng-controller="myController as myCtrl">
...
<div my-directive>...</div>
...
</div>
Error
Error: [$compile:ctreq] Controller 'myController', required by directive 'myDirective', can't be found!
Why?
Maybe, require
property must be reference to a controller of directive?
Thanks
解决方案
Require is of using other directives controllers in another directive , please refer the below example
var App = angular.module('myApp',[]);
//one directive
App.directive('oneDirective',function(){
return {
restrict: 'E',
controller:function($scope){
$scope.myName= function(){
console.log('myname');
}
}
}
});
//two directive
App.directive('twoDirective',function(){
return {
require:'oneDirective' //one directive used,
link : function(scope,ele,attrs,oneCtrl){
console.log(oneCtrl.myName())
}
}
})
这篇关于使用“需要"在指令中要求父控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文