我看过this post。但是,在该示例中,他在侦听元素的单击事件后调用控制器函数。
如何在单击指令元素的子元素时调用控制器函数?
<div ng-controller="MyCtrl">
<abc method1="outerMethod('c')" method2="outerMethod2('g')"></abc>
</div>
指令:
var myApp = angular.module('myApp',[]);
myApp.directive('abc', function() {
return {
restrict: "EA",
replace: true,
template: "<div><p ng-click='clickedP()'>p</p><div ng-click='clickedDiv()'>div</div></div>",
controller: function($scope) {
// how can I call outerMethod if clickedP is executed???
// how can I call outerMethod2 if clickedDiv is executed???
},
controllerAs: "vm",
link: function(scope, element, attrs, vm) {
}
}
});
function MyCtrl($scope) {
$scope.outerMethod = function( a ) {
alert( "you did it" );
}
$scope.outerMethod2 = function( a ) {
alert( "you did it again" );
}
}
答案 0 :(得分:1)
可以直接使用范围而不传递属性。另外,在与父控制器具有相同值的指令上使用“controllerAs”是个坏主意,因为它会覆盖它。
解决方案:
var myApp = angular.module('myApp', []);
myApp.directive('abc', function () {
return {
restrict: "EA",
replace: true,
template: "<div><p ng-click='clickedP()'>p</p><div ng-click='clickedDiv()'>div</div></div>",
controller: function ($scope) {
// how can I call outerMethod if clickedP is executed???
$scope.clickedP = function () {
$scope.outerMethod(); // you just call it!
}
// how can I call outerMethod2 if clickedDiv is executed???
$scope.clickedDiv = function () {
$scope.outerMethod2(); //Same way!
}
},
controllerAs: "vm",
link: function (scope, element, attrs, vm) {
/* It would have been better to handle clickedP and
clickedDiv here instead of in the controller, but I'm
trying to avoid confusion by changing as little as
possible of your code. */
}
}
});
function MyCtrl($scope) {
$scope.outerMethod = function (a) {
alert("you did it");
}
$scope.outerMethod2 = function (a) {
alert("you did it again");
}