Controllers and services can become classes.
I like to use $inject so it's safe to minify, but that line is optional.
class ModalInstanceController {
static $inject = ["$scope", "$modalInstance", "$userService"];
constructor($scope, $modalInstance, $userService) {
$scope.ok = () => {
$modalInstance.close();
};
$scope.cancel = () => {
$modalInstance.dismiss('cancel');
};
}
}
.controller('ModalInstanceCtrl', ModalInstanceController);
Including $inject is equivalent to using the array syntax in vanilla JavaScript:
.controller('ModalInstanceCtrl', ["$scope", "$modalInstance", "$userService", function ($scope, $modalInstance, $userService) { ... }]);
In a real-world application, I like to avoid the use of $scope except for things that actually need it (like $watch), in which case I'd pull the methods out as well. This will require a change to your HTML, though.
class ModalInstanceController {
private $modalInstance : any;
static $inject = ["$modalInstance", "$userService"];
constructor($modalInstance, $userService) {
this.$modalInstance = $modalInstance;
}
ok() {
this.$modalInstance.close();
}
cancel() {
this.$modalInstance.dismiss('cancel');
};
}
Then in your HTML,
<button type="button" ng-click="ModalInstanceCtrl.ok()">OK</button>
Note the use of the fully-qualified ModalInstanceCtrl.ok(), since it's no longer just floating around in the scope.
Just since you caught me when I was bored, here's a nice advantage of using TypeScript, since I see you have $userService.
class UserService {
// A parameterized constructor is, of course, allowed here too.
// Optionally supply $inject, per above
parse(arg : string) {
return parseInt(arg);
}
}
class ModalInstanceController {
private $modalInstance : any;
private $userService : UserService; // Note the typing here
static $inject = ["$modalInstance", "$userService"];
// Explicit typing here is optional, since "any" will cast automatically
// but I like to be clear anyway.
constructor($modalInstance, $userService : UserService) {
this.$modalInstance = $modalInstance;
this.$userService = $userService;
}
ok() {
// you'll get Intellisense here, whilst still benefiting from DI from Angular
var arg = this.$userService.parse("12");
this.$modalInstance.close();
}
cancel() {
this.$modalInstance.dismiss('cancel');
};
}
app.service("$userService", UserService);
app.controller("ModalInstanceCtrl", ModalInstanceController);