moosefetcher moosefetcher - 3 days ago 6
AngularJS Question

Angular 1.2: Trigger page change from directive

I've recently come back to an angular project after some time away and I'm (once again) having some trouble making sense of the angular syntax.

I'd just like to add a link to a button.

Here's the code for the 'directionComponent' module, which is being added correctly, via eng-direction in the html.

var app = angular.module("directionComponent", []);

app.directive('engDirection', function(completions) {
return {
restrict: 'A',
replace: true,
templateUrl: 'components/direction.html',
link: function(scope, element, attrs) {
scope.changePage = function (newPageID) {
console.log("page should change to "+newPageID);
}
}

};
});


The console.log message gets triggered as expected via ng-click but I have very little idea as to how to trigger a page change. Do I need to include $routeParams or $routeProvider somewhere?

I've searched but can't seem to find an answer that meshes with what I'm trying to do and I don't know what I need to change in the solutions I've found to make it work in my case.
If anyone has any pointers, it would be much appreciated.

Answer

You need to inject the $location service:

app.directive('engDirection', ['$location', function($location) { ... }]);

and then in your function:

scope.changePage = function (newPageID) {
    $location.path(newPageID);
}
Comments