[英]Call parent controllers' function from directive in angular
I have a ng-click within a directive named ball
. 我在名为ball
的指令中进行了ng单击。 I am trying to call MainCtrl
's function test()
and alert the value of ng-repeat's alignment
of ball. 我正在尝试调用MainCtrl
的函数test()
并警告ng-repeat's alignment
球ng-repeat's alignment
的值。 Why cant i recognize the MainCtrl's test function? 为什么我无法识别MainCtrl的测试功能? var $scope; var $ scope; var app = angular.module('miniapp', []); var app = angular.module('miniapp',[]);
app.controller('MainCtrl', function($scope) {
$scope.project = {"name":"sup"};
$scope.test = function(value) {
alert(value);
}
$scope.test2 = function(value) {
alert('yo'+value);
}
}).directive('ball', function () {
return {
restrict:'E',
scope: {
'test': '&test'
},
template: '<div class="alignment-box" ng-repeat="alignment in [0,1,2,3,4]" ng-click="test(alignment)" val="{{alignment}}">{{alignment}}</div>'
};
});
html html
<div ng-app="miniapp">
<div ng-controller="MainCtrl">
{{project}}
<ball></ball>
</div>
</div>
You need to pass the test()
method from the controller into the directive... 您需要将test()
方法从控制器传递到指令中...
<div ng-app="miniapp">
<div ng-controller="MainCtrl">
{{project}}
<ball test="test"></ball>
</div>
</div>
Change &
to =
in directive: 在指令中将&
更改为=
scope: {
'test': '=test'
}
Fiddle: http://jsfiddle.net/89AYX/49/ 小提琴: http : //jsfiddle.net/89AYX/49/
the one way is to not isolate a directive scope...just remove the scope object from directive. 一种方法是不隔离指令范围...只需从指令中删除范围对象。
Another way is to implement an angular service and put a common method there, inject this service wherever you need it and in the directive call function that will be insight isolated scope and there call a function from directive 另一种方法是实现一个角度服务,并在其中放置一个通用方法,将该服务注入到您需要的任何地方,并在将成为洞察力隔离范围的指令调用函数中,并从指令中调用函数
You just need to set the controller in your directive as: controller: 'MainCtrl' 您只需要在指令中将控制器设置为:controller:'MainCtrl'
so the code for your directive should look like: 因此您指令的代码应如下所示:
return {
restrict:'E',
scope: {
'test': '&test'
},
template: '<div class="alignment-box" ng-repeat="alignment in [0,1,2,3,4]" ng-click="test(alignment)" val="{{alignment}}">{{alignment}}</div>',
controller: 'MainCtrl'
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.