UNPKG

3.99 kBJavaScriptView Raw
1/**
2 * require the use of controllerAs in routes or states
3 *
4 * You should use Angular's controllerAs syntax when defining routes or states.
5 *
6 * @styleguideReference {johnpapa} `y031` controllerAs Controller Syntax
7 * @version 0.1.0
8 * @category bestPractice
9 * @sinceAngularVersion 1.x
10 */
11'use strict';
12
13var utils = require('./utils/utils');
14
15module.exports = {
16 meta: {
17 schema: []
18 },
19 create: function(context) {
20 return {
21 CallExpression: function(node) {
22 var routeObject = null;
23 var stateObject = null;
24 var hasControllerAs = false;
25 var controllerProp = null;
26 var stateName = null;
27
28 if (utils.isRouteDefinition(node)) {
29 // second argument in $routeProvider.when('route', {...})
30 routeObject = node.arguments[1];
31
32 if (routeObject.properties) {
33 routeObject.properties.forEach(function(prop) {
34 if (prop.key.name === 'controller') {
35 controllerProp = prop;
36
37 if (new RegExp('\\sas\\s').test(prop.value.value)) {
38 hasControllerAs = true;
39 }
40 }
41
42 if (prop.key.name === 'controllerAs') {
43 if (hasControllerAs) {
44 context.report(node, 'The controllerAs syntax is defined twice for the route "{{route}}"', {
45 route: node.arguments[0].value
46 });
47 }
48
49 hasControllerAs = true;
50 }
51 });
52
53 // if it's a route without a controller, we shouldn't warn about controllerAs
54 if (controllerProp && !hasControllerAs) {
55 context.report(node, 'Route "{{route}}" should use controllerAs syntax', {
56 route: node.arguments[0].value
57 });
58 }
59 }
60 } else if (utils.isUIRouterStateDefinition(node)) {
61 // state can be defined like .state({...}) or .state('name', {...})
62 var isObjectState = node.arguments.length === 1;
63 stateObject = isObjectState ? node.arguments[0] : node.arguments[1];
64
65 if (stateObject && stateObject.properties) {
66 stateObject.properties.forEach(function(prop) {
67 if (prop.key.name === 'controller') {
68 controllerProp = prop;
69 }
70 if (prop.key.name === 'controllerAs') {
71 hasControllerAs = true;
72 }
73 // grab the name from the object for when they aren't using .state('name',...)
74 if (prop.key.name === 'name') {
75 stateName = prop.value.value;
76 }
77 });
78
79 if (!hasControllerAs && controllerProp) {
80 // if the controller is a string, controllerAs can be set like 'controller as vm'
81 if (controllerProp.value.type !== 'Literal' || controllerProp.value.value.indexOf(' as ') < 0) {
82 context.report(node, 'State "{{state}}" should use controllerAs syntax', {
83 state: isObjectState ? stateName : node.arguments[0].value
84 });
85 }
86 }
87 }
88 }
89 }
90 };
91 }
92};