Skip to content

Commit e048ef3

Browse files
author
Anatoly Ostrovsky
committed
Refactor ngInject
1 parent 2d35c9f commit e048ef3

File tree

2 files changed

+22
-27
lines changed

2 files changed

+22
-27
lines changed

src/directive/inject/inject.js

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,25 +11,20 @@ export function ngInjectDirective($log, $injector) {
1111
return {
1212
restrict: "A",
1313
link(scope, _element, attrs) {
14-
const expr = attrs["ngInject"];
15-
14+
const expr = attrs.ngInject;
1615
if (!expr) return;
17-
// Match any identifier that starts with $, or ends with Service/Factory
18-
// Example matches: $http, userService, authFactory
19-
const replacedExpr = expr.replace(
20-
/(\$[\w]+|[\w]+(?:Service|Factory))/g,
21-
(match, name) => {
22-
try {
23-
const service = $injector.get(name);
24-
scope.$target[name] = service;
25-
return name;
26-
} catch {
27-
$log.warn(`Injectable ${name} not found in $injector`);
28-
return match;
29-
}
30-
},
31-
);
32-
scope.$apply(replacedExpr);
16+
const tokens = expr
17+
.split(";")
18+
.map((s) => s.trim())
19+
.filter(Boolean);
20+
21+
for (const name of tokens) {
22+
if ($injector.has(name)) {
23+
scope[name] = $injector.get(name);
24+
} else {
25+
$log.warn(`Injectable ${name} not found in $injector`);
26+
}
27+
}
3328
},
3429
};
3530
}

src/directive/inject/inject.spec.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,24 +85,24 @@ describe("ngInject", () => {
8585
expect(el.innerText.trim()).toBe("123");
8686
});
8787

88-
it("should ignore non-$ identifiers", async () => {
89-
el.innerHTML = `<div ng-inject="someVar = 5"> {{ someVar }} </div>`;
90-
$compile(el)($rootScope);
91-
await wait();
92-
expect($rootScope.someVar).toBe(5);
93-
});
94-
95-
it("should inject identifiers ending in *Service", async () => {
88+
it("should inject identifiers for services", async () => {
9689
el.innerHTML = `<div ng-inject="userService"> {{ userService.name }} </div>`;
9790
$compile(el)($rootScope);
9891
await wait();
9992
expect(el.innerText.trim()).toBe("Bob");
10093
});
10194

102-
it("should inject identifiers ending in *Factory", async () => {
95+
it("should inject identifiers for factories", async () => {
10396
el.innerHTML = `<div ng-inject="userFactory"> {{ userFactory.name }} </div>`;
10497
$compile(el)($rootScope);
10598
await wait();
10699
expect(el.innerText.trim()).toBe("Fred");
107100
});
101+
102+
it("should define references anywhere in the template", async () => {
103+
el.innerHTML = `<div>{{ userService.name }} <div ng-inject="userService"></div></div>`;
104+
$compile(el)($rootScope);
105+
await wait();
106+
expect(el.innerText.trim()).toBe("Bob");
107+
});
108108
});

0 commit comments

Comments
 (0)