How to use $ location in directives in AngularJs

I create a directive in which onclick it takes the user to another page. Most likely as a customized "href" tag. I was hoping that $ location would take care of the redirection function, but for reasons I don't know about, this does not work. If I use $ location in the controller, it works, but from inside the Directive it is 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 to have 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 does not work either. What is the problem? And how can you use $ location in directives?

+6
source share
1 answer

So, according to the comment above, every time you call Angular outside Angular your own event handlers ( ng-click , etc.), you should call $scope.$apply() . JQuery events are the most common case when people forget to call $apply() .

+6
source

Source: https://habr.com/ru/post/954836/


All Articles