EmmanuelDemey / EmmanuelDemey/eslint-plugin-angular

Directives and ControllerAs (Y075)

Open
#45 0 comments 0 reactions 0 assignees View on GitHub
Rule
Dominant language
JavaScript
Stars
620
Forks
127
PR merge metrics
No merged PRs in 30d

Description

https://github.com/johnpapa/angularjs-styleguide/edit/master/README.md
- Use `controller as` syntax with a directive to be consistent with using `controller as` with view and controller pairings.

_Why?_: It makes sense and it's not difficult.

Note: The directive below demonstrates some of the ways you can use scope inside of link and directive controllers, using controllerAs. I in-lined the template just to keep it all in one place.

Note: Regarding dependency injection, see [Manually Identify Dependencies](#manual-annotating-for-dependency-injection).

Note: Note that the directive's controller is outside the directive's closure. This style eliminates issues where the injection gets created as unreachable code after a `return`.

``` html


```

``` javascript
angular
.module('app')
.directive('myExample', myExample);

function myExample() {
var directive = {
restrict: 'EA',
templateUrl: 'app/feature/example.directive.html',
scope: {
max: '='
},
link: linkFunc,
controller: ExampleController,
controllerAs: 'vm',
bindToController: true // because the scope is isolated
};

return directive;

function linkFunc(scope, el, attr, ctrl) {
console.log('LINK: scope.min = %s *** should be undefined', scope.min);
console.log('LINK: scope.max = %s *** should be undefined', scope.max);
console.log('LINK: scope.vm.min = %s', scope.vm.min);
console.log('LINK: scope.vm.max = %s', scope.vm.max);
}
}

ExampleController.$inject = ['$scope'];

function ExampleController($scope) {
// Injecting $scope just for comparison
var vm = this;

vm.min = 3;

console.log('CTRL: $scope.vm.min = %s', $scope.vm.min);
console.log('CTRL: $scope.vm.max = %s', $scope.vm.max);
console.log('CTRL: vm.min = %s', vm.min);
console.log('CTRL: vm.max = %s', vm.max);
}
```

``` html

hello world

max={{vm.max}}

min={{vm.min}}

```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.