How to reach a function from a directive that is defined in the inline controller
-
21-12-2019 - |
Question
If I have a directive
, that has its own controller
defined in its body:
directives.directive("formWrapper", ['User','$location', function(User, $location) {
return {
...
template: '<div>' +
'<input ng-click="cancel()" type="button" value="Cancel"/>' +
'<input ng-click="save()" type="button" value="Save" />' +
'</div>',
controller: function($scope, $location, User) {
$scope.fields = User.get( {username: "username"} );
var save = function() {...}
var cancel = function() {...}
}
}
}]);
In a template
section I'm trying to reach functions save()
and cancel()
which are defined in the controller.
For now it does not work clicking on those buttons nothing happens.
I really don't want to define
save()
andcancel()
in the$scope
, because only this directive is supposed to use them. Or maybe it is ok to make them being in the$scope
? Not sure about that isolation.
Q: How can I achieve it? Some common solution / vision about that?
Solution
You need to put save()
and cancel()
on the directive's scope so the template can see them (right now they're only visible inside the controller function).
So instead of:
var save = function() {...}
var cancel = function() {...}
You want
$scope.save = function() {...}
$scope.cancel = function() {...}
It's fine for these to be on the directive scope. It's not like putting them on $rootScope
which is global.
You'll notice I added this to your directive:
scope: {},
That makes this $scope
restricted to just this directive (AKA "isolated scope"). So you can think of this like an object or function scope- you're not polluting global namespace.
Here's a demo: http://jsfiddle.net/uLfLM/1/