有一个需求,需要在指令中调用指令所在controller里的方法,我举个简单的例子,代码如下:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="directive.js"></script>
</head>
<body ng-controller="myCtrl">
<my-dir my-click='click()'></my-dir>
</body>
</html>
controller和directive的代码如下:
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.click= function(param){
console.log(param);
}
}
app.directive('myDir',
function(){
return {
restrict:'AE',
replace: true,
template: '<input ng-click="inputClick()"></input>',
scope:{
myClick : '&'
},
link:function(scope,elem,attr){
scope.inputClick = function(){
scope.myClick("123");
}
}
}
}
);
使用这种方式,倒是可以调用到controller里的click方法,但是参数没法传递过去,打印出来的param始终是undefined,是不是我这种调用方式压根就是错误的啊,那么如何应对这种需求呢,求大神指教,在线等,谢了!!!
http://stackoverflow.com/questions/23636727/how-to-call-controller-function-from-directive