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?
Overview. The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
The best way to pass an object to an angular directive is by using the &. When you use &, angular compiles the string as an expression and sets the scope variable in your directive to a function that, when called, will evaluate the expression in the context of the directive's parent's scope.
$location.absUrl() We can get full url of current web page. $location.url() It returns url without base prefix.
AngularJS Directive's link key defines link function for the directive. Precisely, using link function, we can define directive's API & functions that can then be used by directive to preform some business logic. The link function is also responsible for registering DOM listeners as well as updating the DOM.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With