Reputation: 11
I have a function in my controller name as enableEditor it is working if i call the function from direct HTML i.e(add). But, if I call the function for a element which is created through the directives i.e(edit) is not working. Please look at my code and advice me if 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>
Upvotes: 0
Views: 426
Reputation: 20014
Since you have an isolated scope the function belongs to the scope of the directive not your controller. Try using &
in your directives scope like this:
<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 attribute callme="enableEditor()"
is used to pass the method to the scope directive, the directive scope uses &
to indicate it is method callme:"&"
. Another example:
method2="someMethod()"
like
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>'
Upvotes: 2