Define function inside Angular directive's isolated scope
The only legal values for an isolated scope object definition are strings which begin with &
, @
, or =
. (You can also follow these symbols with the name of the property on the parent scope should you want the property name to differ within the directive.1) In this instance you want to use the =
symbol as this indicates that Angular should "bind changePage
on the directive scope to changePage
on the parent scope". Take a look at this answer for more details.
You're right that it is ugly having to pass this function in via an attribute on the directive, however this is the nature of having an isolated scope. You might consider having the changePage
and other related methods in a service, as you can then inject this as a dependency.
Edit
Without an isolate scope you could do the following:
module.directive("pagination", function() {
return {
restrict: "E",
templateUrl: "templates/pagination.html",
link: function(scope, elem, attrs) {
// scope.changePage is available from the directive's parent $scope
}
}
}
1 Example: { 'nameInDirective': '=nameOnParent' }
As user sdgluck answers correctly you can extend the directive scope in the link function and thus keep your code clean and separate. Following sample is a little more complete but it boils down to the same result. It allows you to define an element as below. Be aware that all attributes are interpreted as objects, and, if you want to pass a string value you have to put the extra quotes around that value (or you'll get an undefined value for that attribute)
<my-button someattr="'my text'"></my-button>
angular.module('test', []);
angular.module('test').controller('testctrl', function($scope) {
$scope.someValue = '';
});
angular.module('test').directive('myButton', function() {
return {
restrict: 'E',
template: '<button>{{getText()}}</button>',
replace: true,
scope: {
someattr: '='
},
link: function(scope, elements, attrs){
scope.getText = function(){
return scope.someattr;
};
}
}
});