6. Kontroler – JavaScript’owy konstruktor
// JavaScript Constructor
function Car(){
this.model = 'RANGE ROVER';
this.price = 300000;
this.engine = '3.0 V6'
}
// za każdym razem kiedy otwieramy kontroler, tworzymy nową instancję
var sale = new Car();
8. Składnia - Controller As
angular
.module('app.cars')
.controller('Car', Car);
function Car(){
var vm = this;
vm.model = 'RANGE ROVER';
vm.price = 300000;
vm.engine = '3.0 V6';
}
vm = this
23. Controller As bez $scope
<div ng-controller="Ctrl1 as vm">
Ctrl1: {{vm.test}}
<div ng-controller="Ctrl2 as vm">
Ctrl2: {{vm.test}}
<div ng-controller="Ctrl3 as vm">
Ctrl3: {{vm.test}}
</div>
</div>
</div>
24. Gdzie jest $scope?
(function () {
angular
.module('app', [])
.controller('Ctrl1', Ctrl1)
.controller('Ctrl2', Ctrl2)
.controller('Ctrl3', Ctrl3);
function Ctrl1() {}
function Ctrl2() { var vm = this; vm.test = 'test 2';}
function Ctrl3() {}
})();
26. Czy można bardziej czytelnie?
<div ng-controller="Ctrl1 as ctrl1">
Ctrl1: {{ctrl1.test}}
<div ng-controller="Ctrl2 as ctrl2">
Ctrl2: {{ctrl2.test}}
<div ng-controller="Ctrl3 as ctrl3">
Ctrl3: {{ctrl3.test}}
</div>
</div>
</div>
Podmieniamy vm na nazwę kontrolera
27. Ale nic nie zmieniamy w kodzie JavaScript!
(function () {
angular
.module('app', [])
.controller('Ctrl1', Ctrl1)
.controller('Ctrl2', Ctrl2)
.controller('Ctrl3', Ctrl3);
function Ctrl1() {}
function Ctrl2() { var vm = this; vm.test = 'test 2';}
function Ctrl3() {}
})();
Tu nadal pozostaje vm
28. ctrl2 jest rozpoznane jako vm
<div ng-controller="Ctrl2 as ctrl2">
Ctrl2: {{ctrl2.test}}
function Ctrl2() {
var vm = this;
vm.test = 'test 2';
}
29. A jeśli przypiszemy vm do $scope?
(function () {
angular
.module('app', [])
.controller('Ctrl1', Ctrl1)
.controller('Ctrl2', Ctrl2)
.controller('Ctrl3', Ctrl3);
Ctrl1.$inject = ['$scope'];
function Ctrl1($scope) { $scope.vm = this; }
Ctrl2.$inject = ['$scope'];
function Ctrl2($scope) { $scope.vm = this; $scope.vm.test = 'test 2'; }
Ctrl3.$inject = ['$scope'];
function Ctrl3($scope) { $scope.vm = this; }
})();
Nie zalecane!