dade
dade

Reputation: 3570

How to use $location in Directives in AngularJs

I am creating a directive in which onclick it takes the user to another page. Somewhat like a customized "href" tag. I was hoping $location would take care of the redirection function but for reasons I do not know yey, this does not work. If I use $location in a controller it works but from within a Directive, it does not. Here is the code:

angular.module("myAPP")
    .directive('hpHref', ['$location' , function($location){
        return {
            restrict : "A",
            link : function(scope, el, attr) {
                    el.bind('click', function(){
                        // more logic
                        console.log("Code reaches here:");
                        $location.path("/" + attr.hpHref);
                    });
            }
        }
    }]);

Also tried having a controller as part of the Directive. i.e.

angular.module("myApp")
    .directive('hpHref', function(){
        return {
            restrict : "A",
            scope: {},
            controller : ['$scope', '$location', function($scope, $location){
                $scope.goToUrl = function (url) {
                    // some more logic
                    console.log("Code reaches here");
                    $location.path(url);
                };
            }],
            link : function(scope, el, attr) {
                    el.bind('click', function(){
                        scope.goToUrl(attr.hpHref); 
                    });
            }
        }
    });

This too does not work. What is the problem? And how can $location be used within Directives?

Upvotes: 6

Views: 4189

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

So, as per the comment above, any time you call Angular outside of Angular's own event handlers (ng-click etc), you have to call $scope.$apply(). JQuery events are the most common case people forgetto call $apply().

Upvotes: 6

Related Questions