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() and cancel() 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?

Was it helpful?

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top