I want to communication between directive and controller. so write this sample code but it not work!what is my problem? do have another way for this issue?
var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function ($scope) { var vm = this; vm.directiveButtonClicked = function () { // Controller reacting to call initiated by directive alert('Button was clicked in directive'); console.log("dfg dfg dfg dfg"); } }); myApp.directive("myDirective",function(){ return { restrict: 'E', template: '<button ng-click="buttonClicked">Click Me</button>', scope: { onButtonClick: '&' }, link: link }; function link(scope, element, attrs, controller) { scope.buttonClicked = function () { // Button was clicked in the directive // Invoke callback function on the controller scope.onButtonClick(); } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl as vm"> <my-directive on-button-click="vm.directiveButtonClicked" /> </div>
You need to add ()
to functions in both on-button-click
and ng-click
:
var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function ($scope) { var vm = this; vm.directiveButtonClicked = function () { // Controller reacting to call initiated by directive alert('Button was clicked in directive'); console.log("dfg dfg dfg dfg"); }; }); myApp.directive("myDirective",function(){ return { restrict: 'E', template: '<button ng-click="buttonClicked()">Click Me</button>', scope: { onButtonClick: '&' }, link: link }; function link(scope, element, attrs, controller) { scope.buttonClicked = function () { // Button was clicked in the directive // Invoke callback function on the controller scope.onButtonClick(); }; } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl as vm"> <my-directive on-button-click="vm.directiveButtonClicked()" /> </div>
Just remove ng-click and use this instead:
element.click(function() { scope.onButtonClick(); });
Look at the plunker .
In your directive, you are trying to access a function defined in the controller. But while defining your directive in view, you are not passing the correct reference to your function. Try this: <my-directive on-button-click="vm.directiveButtonClicked" />
Instead of: <my-directive on-button-click="vm.directiveButtonClicked()" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.