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

Angular #5

Angular #5

Danila Marchenkov

August 17, 2017
Tweet

More Decks by Danila Marchenkov

Other Decks in Education

Transcript

  1. SPA 5 При перезагрузке страницы сам клиент не знает в

    каком состоянии он находился до перезагрузки. Проблема:
  2. Under the hood Роутер - метод сопоставлений $location.url() существующему роуту.

    Набор роутов - one-to-one map существующих контроллеров некоторому паттерну URL Вместе контроллера может использоваться элементная директива или компонента Роутер следит на изменениями $location.url и в соответсвии с изменениями отдаёт нужный роут 8
  3. 9

  4. 11

  5. 12 .config(function($routeProvider, $locationProvider) { $routeProvider .when('/Book/:bookId', { templateUrl: 'book.html', controller:

    'BookController', resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }) .when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: 'ChapterController' }); });
  6. Pros & Cons • + Сохранение состояния приложения по URL-у

    • + Параметризированные роуты • + resolve • + $routeChangeSuccess, $routeChangeStart, $routeChangeError • — Невозможность создания параллельных роутов • — Неудобство конфигурации • — DEPRECATED :) 13
  7. 15 name - a name for the state, providing a

    way to refer to the state views - How the UI will look and behave url -What the browser’s URL will be params -Parameter values that the state requires (such as blog-post-id) resolve -The actual data the state requires (often fetched, asynchronously, from the backend using a parameter value)
  8. Activating a state There are three main ways to activate

    a state: 1. Call $state.go(). High-level convenience method. 2. Click a link containing the ui-sref directive. 3. Navigate to the url associated with the state. 16
  9. URL matching 17 • '/hello/' - Matches only if the

    path is exactly '/hello/'. There is no special treatment for trailing slashes, and patterns have to match the entire path, not just a prefix. • '/user/:id' - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/ user' or '/user/bob/details'. The second path segment will be captured as the parameter 'id'. • '/user/{id}' - Same as the previous example, but using curly brace syntax. • '/user/{id:int}' - The param is interpreted as Integer. • ‘/user/{id:[^/]*}’ - regExp • ‘^/list’ - absolute route
  10. Resolve 18 $stateProvider.state('parent', { resolve:{ resA: function() { return {'value':

    'A'}; } }, controller: function($scope, resA){ $scope.resA = resA.value; } }) .state('parent.child', { resolve:{ resB: function(resA) { return {'value': resA.value + 'B'}; } }, controller: function($scope, resA, resB){ $scope.resA2 = resA.value; $scope.resB = resB.value; }
  11. Data 19 $stateProvider .state('parent', { data:{ customData1: "Hello", customData2: "World!"

    } }) .state('parent.child', { data:{ // customData1 inherited from 'parent' // but we'll overwrite customData2 customData2: "UI-Router!" } }); $rootScope.$on('$stateChangeStart', function(event, toState){ var greeting = toState.data.customData1 + " " + toState.data.customData2; console.log(greeting); // Would print "Hello World!" when 'parent' is activated // Would print "Hello UI-Router!" when 'parent.child' is activated })
  12. LazyLoad 20 var mystate = { name: 'messages', url: '/messages',

    component: messages, lazyLoad: function() { return System.import('moment'); } }
  13. 22 +---------+---------------------------------+ |*INBOX* | MESSAGE1 | | SPAM | *MESSAGE2*

    | | DELETED | MESSAGE3 | | SENT +---------------------------------+ | | MESSAGE 2 CONTENT | | | | | | | | | | +---------+---------------------------------+ +---------+---------------------------------+ |*INBOX* | MESSAGE1 | | SPAM | *MESSAGE2* | | DELETED | MESSAGE3 | | SENT +---------------------------------+ | | MESSAGE 2 CONTENT | | | | | | | | | | +---------+---------------------------------+ Nested routes folder list -> message list -> message content.
  14. Nested routes • Configuring • dot.notation • .state(‘contacts.list’, {}) •

    parent property <string|Object> • Conventions • name - уникально 23
  15. Named Views 24 <body> <div ui-view=“filters"></div> <div ui-view="tabledata"></div> <div ui-view=“graph"></div>

    </body> $stateProvider .state('report',{ views: { 'filters': { templateUrl: 'report-filters.html', controller: function($scope){ ... controller stuff just for filters view ... } }, 'tabledata': { templateUrl: 'report-table.html', controller: function($scope){ ... controller stuff just for tabledata view ... } }, 'graph': { templateUrl: 'report-graph.html', controller: function($scope){ ... controller stuff just for graph view ... } } } })
  16. Abstract states • To prepend a url to all child

    state urls. • To insert a template with its own ui-view(s) that its child states will populate. • Optionally assign a controller to the template. The controller must pair to a template. • Additionally, inherit $scope objects down to children, just understand that this happens via the view hierarchy, not the state hierarchy. • To provide resolved dependencies via resolve for use by child states. • To provide inherited custom data via data for use by child states or an event listener. • To run an onEnter or onExit function that may modify the application in someway. • Any combination of the above. 25
  17. $scope inheritance 26 $stateProvider .state('contacts', { abstract: true, url: '/contacts',

    templateUrl: 'contacts.html', controller: function($scope){ $scope.contacts = [{ id:0, name: "Alice" }, { id:1, name: "Bob" }]; } }) .state('contacts.list', { url: '/list', templateUrl: 'contacts.list.html' }) .state('contacts.detail', { url: '/:id', templateUrl: 'contacts.detail.html', controller: function($scope, $stateParams){ $scope.person = $scope.contacts[$stateParams.id]; } })
  18. Abstract state 27 .state(‘logged', { abstract: true, url: '/contacts', //

    Note: abstract still needs a ui-view for its children to populate. // You can simply add it inline here. template: '<ui-view/>' })