6

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?

5
  • It doesn't work because you are trying to set the path to the literal string "url", not the value of the url argument. Remove the quotes around url in $location.path("url") Commented Sep 28, 2013 at 12:07
  • @MarkSherretta That was a typo in copying the code over here. I have updated the question Commented Sep 28, 2013 at 12:12
  • Now, what's $apply.goToUrl? Commented Sep 28, 2013 at 12:13
  • You have to call $scope.apply() after changing the location inside a jQuery event handler. Commented Sep 28, 2013 at 13:40
  • @NikosParaskevopoulos Ha! Remembered that .bind is powered by JQuery lite included in AngularJs...so yes, your suggestion works! Mind putting it as an answer so it can be accepted? Commented Sep 28, 2013 at 16:16

1 Answer 1

6

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().

Sign up to request clarification or add additional context in comments.

1 Comment

$scope.$apply() where? inside element.on('click', function(){})?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.