Prototype based controller with Angular 1.4
30 ביוני 2015
I just encountered a brilliant post written by Eyal Vardi (Hebrew only)
Eyal talks about how we can use Angular metadata stored inside $inject to automatically inject the controller's dependencies into the controller instance
This way you don't need to manually copy local dependency parameters into the controller instance.
Consider the following Typescript controller + HTML view
class HomeCtrl {
$scope;
$http;
items: any;
constructor($scope, $http) {
this.$scope = $scope;
this.$http = $http;
}
refresh() {
this.$http.get("/api/item").then((items) => {
this.items = items;
});
}
}
angular.module("MyApp").controller("HomeCtrl", );
<div ng-controller="HomeCtrl as ctrl">
<ul>
<li ng-repeat="item in ctrl.items">
<span>{{item.name}}</span>
</li>
</ul>
<div>
<button ng-click="ctrl.refresh()">Refresh</button>
</div>
</div>
As you can see all dependencies specified by angular.controller function are copied manually into the controller instance so we can later use them inside the refresh function.
When writing "plain" Angular controller based on simple function (without prototype) the dependencies are specified as local parameters...
no comments