-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathstateDirectives.js
51 lines (43 loc) · 1.4 KB
/
stateDirectives.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
function parseStateRef(ref) {
var parsed = ref.match(/^([^(]+?)\s*(\((.*)\))?$/);
if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1], paramExpr: parsed[3] || null };
}
$StateRefDirective.$inject = ['$state'];
function $StateRefDirective($state) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var ref = parseStateRef(attrs.uiSref);
var params = null, url = null;
var isForm = element[0].nodeName === "FORM";
var attr = isForm ? "action" : "href", nav = true;
var update = function(newVal) {
if (newVal) params = newVal;
if (!nav) return;
var newHref = $state.href(ref.state, params);
if (!newHref) {
nav = false;
return false;
}
element[0][attr] = newHref;
};
if (ref.paramExpr) {
scope.$watch(ref.paramExpr, function(newVal, oldVal) {
if (newVal !== oldVal) update(newVal);
}, true);
params = scope.$eval(ref.paramExpr);
}
update();
if (isForm) return;
element.bind("click", function(e) {
if ((e.which == 1) && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
$state.go(ref.state, params);
scope.$apply();
return false;
}
});
}
};
}
angular.module('ui.router.state').directive('uiSref', $StateRefDirective);