我的控制器是-
var App = angular.module("App",[]);
App.controller("MainController",['$scope',function($scope){
$scope.getDetail = function(){
console.log("get detail call from main controller");
}
}]);指令是-
App.directive('customDirective',[function(){
return {
restrict : 'EAC',
scope : {
},
template :'<div><button type="button">click here to get detail</button></div>',
link : function(scope,element,attribute){
}
};
}]);页面html是-
<div ng-controller="MainController">
<custom-directive></custom-directive>
</div>我试图在点击自定义指令中的按钮时调用MainController中的getDetail。
发布于 2016-05-06 14:15:46
你听说过隔离作用域吗..这是控制器和嵌套指令之间的连接方式
<div ng-controller="MainController">
<custom-directive="getDetail()"></custom-directive>
</div>
var App = angular.module("App",[]);
App.controller("MainController",['$scope',function($scope){
$scope.getDetail = function(){
console.log("get detail call from main controller");
}
}]);
App.directive('customDirective',[function(){
return {
restrict : 'EAC',
scope : {
customDirective:'&'
},
template :'<div><button type="button" ng-click="heyimclick()">click here to get detail</button></div>',
link : function(scope,element,attribute){
scope.heyimclick=function(){
customDirective();
}
}
};
}]);发布于 2016-05-06 14:53:40
有两种可能的方法:
父控制器作用域
默认情况下,您编写的任何指令都可以访问父控制器作用域,这意味着该指令可以直接调用父控制器函数,而无需任何额外的麻烦。要以这种方式执行任务,指令代码应该是这样的:
App.directive('customDirective',[function(){
return {
restrict : 'EAC',
template :'<div><button type="button" ng-click="getDetail()">click here to get detail</button></div>',
link : function(scope,element,attribute){
//Call the controller function directly in using the scope object
}
};
}]);在这种技术中,指令可以访问父控制器的整个作用域,并且该指令可以直接使用父控制器作用域。如果您只想在一个控制器上使用该指令,这种方法非常有用,因为这会降低该指令的可重用性。
孤立作用域
编写指令的第二种更好的方法是隔离作用域技术。在这种情况下,指令不能直接访问父控制器作用域,而指令要访问的函数将向下传递给它。可以这样想,在两个陆地区域之间存在一堵墙,并且只允许在这两个陆地之间有选择地进入。要使用此技术,您的代码应如下所示:
调用指令的HTML代码:
<div ng-controller="MainController">
<custom-directive detail-function="getDetail()"></custom-directive>
</div>方向块:
App.directive('customDirective',[function(){
return {
restrict : 'EAC',
scope : {
detailFunction='&'
},
template :'<div><button type="button" ng-click='detailFunction()'>click here to get detail</button></div>',
link : function(scope,element,attribute){
}
};
}]);以下链接包含您问题的演示。Sample Code
Referene
https://stackoverflow.com/questions/37065473
复制相似问题