Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Angular-2

 Angular-2

Danila Marchenkov

August 08, 2017
Tweet

More Decks by Danila Marchenkov

Other Decks in Programming

Transcript

  1. Директивы • Встроенные • ng-app, ng-controller, ng-if, ng-show, ng-repeat <div

    ng-app=“myApp" ng-init="names = [ { name: 'Jani', country: 'Norway' }, { name: 'Hege', country: 'Sweden' }, { name: 'Kai', country: 'Denmark' } ]"> <ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.country }} </li> </ul> </div>
  2. Ng-if vs Ng-show <p ng-if="false">This is the partial for view

    1.</p> <p ng-show="false">This is the partial for view 1.</p>
  3. $scope • Связующее звено между контроллером и представлением • Область

    видимости контроллера • Контекст выполнения интерполяций представления • Локальное хранилище данных
  4. Структура $scope • Основной $root-scope • Дочерние изолированные $scope •

    Каждый дочерний $scope имеет доступ к $rootScope • Связь изолированных $scope’ов остается на усмотрение разработчика
  5. Связь изолированных $scope <mld-left-navigation-panel basket="vm.showBasket" experiment="vm.experiment" step-info="vm.stepInfo" add-analysis="vm.addAnalysis()"> </mld-left-navigation-panel> scope:

    { experiment: ‘<', showBasket: ‘=basket', stepInfo: '=', addAnalysis: '&', heading: '@' // string }, analysis-view.html left-navigation-panel.directive.js
  6. $scope.$watch( function () { return this.changes(this.someVar) }, function (newValue, oldValue,

    scope) { //Do anything with $ctrl.someVar }); $scope.$watch( $interpolate( "Interpolate: Best friend is {{ bestFriend.name }}" ), function (newValue, oldValue, scope) { //Do anything with $scope.letters });
  7. $digest цикл • Цикл проверки изменений модели. • Запускается с

    помощью • Директив-обработчиков пользовательских эвентов e.g. ng-click • $scope.$apply(func) • $scope.$digest()
  8. $scope.apply = (f) => { try { $scope.$eval(f); } catch

    (e) { console.error(e); } $scope.$digest() }
  9. Angular expressions • Передача параметров в методы через html •

    Простейший - <span class="big">{{ points }}</span> • Angular template syntax • Логические и тернарные выражения • Математические операции и обращение к полю объекта • вызов функций • pipe-постфикс | • ::-префикс
  10. $parse function (s, l) { if (s == null) return

    undefined; s = ((l && l.hasOwnProperty("data")) ? l : s).data; return s; }
  11. ng-href The wrong way to write it: <a href=“http://www.gravatar.com/avatar/{{hash}}">link1</a> The

    correct way to write it: <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  12. Custom directives At a high level, directives are markers on

    a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
  13. Directive API .directive('ngCourse', ['inj', 'someOtherInj', function(inj, someOtherInj) { return {

    restrict: 'E', transclude: false, scope: { someProp: '=' }, controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, controllerAs: 'ngCourseCtrl', templateUrl: ‘./ng-course.html’, compile: function (tElement, tAttrs, transclude) { return { pre: function (scope, iElement, iAttrs, controller) { ... }, post: function (scope, iElement, iAttrs, controller) { ... } } } }; }]);
  14. Directive lifecycle hooks • .compile(elementRef, attributes) - компиляция темплейта (1х)

    • controller - инициализация контроллера • .preLink($scope, elementRef, attributes) - доступен $scope, доступ к данным из родителя(Nx) • .postLink($scope, elementRef, attributes) - конечный хук инициализации директивы, все дочерние директивы инициализованы (1x)
  15. Внешний api объект <my-web-component api="main.webComponentApi"></my-web-component> app.directive('myWebComponent', function() { return {

    bindToController: { api: '=' }, template: ..., controller: function() { this.api = { setPerson: function(newPerson) { vm.person = newPerson; } }; }, }; });
  16. Пожалуйста! • НЕ работайте с DOM-деревом где-либо, кроме compile и

    pre-link функций • Изолируйте логику в мельчайшие компоненты • Старайтесь разрабатывать stateless компоненты • Используйте встроенные обработчики событий