This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 135
/
ngLink.js
74 lines (66 loc) · 2.2 KB
/
ngLink.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @name ngLink
* @description
* Lets you link to different parts of the app, and automatically generates hrefs.
*
* ## Use
* The directive uses a simple syntax: `ng-link="componentName({ param: paramValue })"`
*
* ### Example
*
* ```js
* angular.module('myApp', ['ngComponentRouter'])
* .controller('AppController', ['$rootRouter', function($rootRouter) {
* $rootRouter.config({ path: '/user/:id', component: 'user' });
* this.user = { name: 'Brian', id: 123 };
* });
* ```
*
* ```html
* <div ng-controller="AppController as app">
* <a ng-link="user({id: app.user.id})">{{app.user.name}}</a>
* </div>
* ```
*/
module.exports = function ngLinkDirective($rootRouter, $parse) {
return {require: '?^^ngOutlet', restrict: 'A', link: ngLinkDirectiveLinkFn};
function ngLinkDirectiveLinkFn(scope, element, attrs, ctrl) {
var router = (ctrl && ctrl.$$router) || $rootRouter;
if (!router) {
return;
}
var navigationInstruction = null;
var link = attrs.ngLink || '';
function getLink(params) {
navigationInstruction = router.generate(params);
scope.$watch(function() { return router.isRouteActive(navigationInstruction); },
function(active) {
if (active) {
element.addClass('ng-link-active');
} else {
element.removeClass('ng-link-active');
}
});
var navigationHref = navigationInstruction.toLinkUrl();
return $rootRouter._location.prepareExternalUrl(navigationHref);
}
var routeParamsGetter = $parse(link);
// we can avoid adding a watcher if it's a literal
if (routeParamsGetter.constant) {
var params = routeParamsGetter();
element.attr('href', getLink(params));
} else {
scope.$watch(
function() { return routeParamsGetter(scope); },
function(params) { return element.attr('href', getLink(params)); },
true);
}
element.on('click', function(event) {
if (event.which !== 1 || !navigationInstruction) {
return;
}
$rootRouter.navigateByInstruction(navigationInstruction);
event.preventDefault();
});
}
};