How to access controller functions in isolated scope directives?

I have a function in my controller name as enableEditor , it works if I call the function from direct HTML ie (add). But, if I call a function for an element that is created through ie (edit) directives, it does not work. Please take a look at my code and advise me if you have any ideas.

<!doctype html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Example - example-example53-production</title> <script src="js/angular.min.js"></script> </head> <body ng-controller="MainCtrl"> <div user-name=""></div> <div> <a href="#" ng-click="enableEditor()">add</a> </div> <script> var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', ['$scope','$filter', function ($scope,$filter) { $scope.enableEditor = function() { alert("123"); }; }]); myApp.directive("userName", function() { return { restrict: "A", scope: { value: "=userName" }, template: '<div class="click-to-edit">' + '<a href="#" ng-click="enableEditor()">Edit</a>' + '</div>' }; }); </script> </body> </html> 
0
angularjs
source share
1 answer

Since you have an isolated scope, the function belongs to the scope of the directive and not to your controller. Try using & in the scope of your directives as follows:

 <body ng-controller="MainCtrl"> <div user-name="" callme="enableEditor()"></div> <div> <a href="#" ng-click="enableEditor()">add</a> </div> <script> var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', ['$scope','$filter', function ($scope,$filter) { $scope.enableEditor = function() { alert("123"); }; }]); myApp.directive("userName", function() { return { restrict: "A", scope: { value: "=userName", callme:"&" }, template: '<div class="click-to-edit">' + '<a href="#" ng-click="callme()">Edit</a>' + '</div>' }; }); 

The callme="enableEditor()" attribute is used to pass the method to the scope directive; in the scope of the directive, & used to indicate that this is the callme:"&" method. Another example:

method2="someMethod()" as

 scope: { value: "=userName", callme:"&", method2:"&" },template: '<div class="click-to-edit">' + '<a href="#" ng-click="callme()">Edit</a>' + '<a href="#" ng-click="Method2()">Save</a>' + '</div>' 
+2
source share

All Articles