Last active
January 13, 2017 21:17
-
-
Save fesor/2b2889446ae97030bc04 to your computer and use it in GitHub Desktop.
Angular Components Evolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Контроллеры не особо видоизменились. | |
// Единственное что поменялось - больше ненадо использовать $scope. | |
class MyComponentController { | |
constructor(myService) { | |
this.myService = myService; | |
} | |
doSomething() { | |
this.myService.doSomething(); | |
} | |
} | |
// шаблон в принципе не изменился. | |
// От версии к версии добавлялись примитивы | |
// но мы не будем акцентировать на этом внимание внимание | |
const template = ` | |
<div class="my-component"> | |
<button ng-click="myComponent.doSomething()"></button> | |
</div> | |
`; | |
angular | |
.module('app') | |
// Angular 1.5 | |
.component('myComponent', { | |
bindings: { | |
'myStuff': '=' | |
}, | |
template: template, | |
controller: MyComponentController | |
}) | |
// Angular 1.3+ | |
.directive('myComponent', function() { | |
return { | |
restrict: 'E', | |
scope: { | |
myStuff: '=' | |
}, | |
bindToController: true, | |
template: template, | |
controller: MyComponentController, | |
controllerAs: 'myComponent' | |
}; | |
}) | |
// Angular 1.2+ | |
.directive('myComponent', function() { | |
return { | |
restrict: 'E', | |
require: 'myComponent' | |
scope: { | |
myStuff: '=' | |
}, | |
template: template, | |
controller: MyComponentController, | |
controllerAs: 'myComponent', | |
link: function(scope, element, attrs, ctrl) { | |
// нам приходится пробрасывать данные в контроллер | |
scope.$watch('myStuff', (value) => { | |
ctrl.myStuff = value; | |
}); | |
} | |
}; | |
}) | |
// Angular 1.0+ | |
.directive('myComponent', function($injector) { | |
const alias = 'myComponent'; | |
return { | |
restrict: 'E', | |
require: 'myComponent' | |
scope: { | |
myStuff: '=' | |
}, | |
template: template, | |
link: function(scope, element, attrs) { | |
scope[alias] = $injector.instantiate(MyComponentController); | |
// нам приходится пробрасывать данные в контроллер | |
scope.$watch('myStuff', (value) => { | |
scope[alias].myStuff = value; | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment