AngularJS dependency injection working example..
HTML
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<button ng-click="test()">Test</button>
<button ng-click="test2()">Test2</button>
</div>
<!-- <div ng-controller="MyAppController">
<button ng-click="notifyUser()">Test2</button>
</div> -->
</div>
JavaScript
var app = angular.module('myApp', []);
app.factory('MyFactory', function() {
return {
test: function() {
console.log('Hello world!');
}
};
});
app.service('NotificationService', class NotificationService {
notify() {
// Send notification
console.log('send notification')
}
});
/* app.controller('MainCtrl', ['$scope', 'MyFactory', function($scope, MyFactory) {
$scope.test = MyFactory.test;
} ]); */
app.controller('MainCtrl', class MainCtrl {
constructor ($scope, MyFactory) {
$scope.test = MyFactory.test;
}
});
/* app.controller('MyAppController', class MyAppController {
constructor(NotificationService) {}
notifyUser() {
this.NotificationService.notify();
}
}); */