javascript - AngularJs: Calling contoller method from directive inside another directive -
i have directive inside directive. outer directive shares scope controller, while inner 1 has own. i'd pass reference controller's function inner directive can called there. cannot figure out how pass function , parameters inner directive can call controller's function.
here planker illustrate problem.
if click on "dir 2 click me" alert says parameters have came undefined.
you can pass in outer controller method using '='
, adjust code accordingly...
angular.module('app', []) .controller('ctrl', function($scope){ $scope.myctrlmethod = function(msg, b) { alert(msg + ' , b='+b); }; }) .directive('dir1', [function(){ return { restrict: 'e', replace: true, template: '<div><p ng-click="mydir1method(\'my dir1 method\',\'b\')">dir 1 click me</p><dir2 my-ctrl-method="myctrlmethod"></dir2></div>', link: function(scope, elem, attrs){ scope.mydir1method = function(msg,b){ scope.myctrlmethod(msg, b); }; } }; }]) .directive('dir2', [function(){ return { restrict: 'e', scope: { myctrlmethod: '=' }, replace: true, template: '<p ng-click="mydir2method(\'my dir2 method\',\'b\')">dir 2 click me</p>', link: function(scope, elem, attrs){ scope.mydir2method = function(msg,b){ scope.myctrlmethod(msg, b); }; } }; }]);
plunker: http://plnkr.co/edit/xbsnxasmzwa3g1gsh6af?p=preview
edit: '='
evaluates expression in context of parent scope , result bound property on inner scope. in example, 'myctrlmethod' evaluated against parent scope, returns myctrlmethod
parent scope (a function). function bound myctrlmethod
on inner scope, , can invoked scope.myctrlmethod(msg, b)
.
Comments
Post a Comment