toddmotto / ama

Ask me anything!
20 stars 3 forks source link

Lifecycle hooks with UI router 1.0 child states #73

Closed blowsie closed 7 years ago

blowsie commented 7 years ago

Hey @toddmotto,

I thought id come to you with this is issue as it is your Angular JS course that got my inspired and using angular components. :)

I've started implementing ui-router child states such as contact, contact.edit and contact.view.

My question is, how can I implement an onUpdate lifecycle hook to contact.edit with the state configuration options?

Some code, condensed to give you an idea of what in trying to achieve

(function() {
  'use strict';

  angular
      .module('app')
      .config(routerConfig);

  /** @ngInject */
  function routerConfig($stateProvider) {
    $stateProvider
        .state('contact', {
          parent: 'app',
          url: '/contacts/:contactId',
          component: 'contact',
          redirectTo: 'contact.view',
          resolve: {
            contact: function(ContactResource, $stateParams) {
              return ContactResource.contacts.get(
                  {
                    contactId: $stateParams.contactId
                  }
              ).$promise
            }
          }
        });
    $stateProvider
        .state('contact.edit', {
          component: 'contactEdit'
        });
    $stateProvider
        .state('contact.view', {
          component: 'contactView'
        });
  }

})();

(function() {
  'use strict';

  angular
      .module('app')
      .component('contact', {
        restrict: 'E',
        bindings: {
          contact: '<'
        },
        templateUrl: 'app/components/contact/contact/contact.html',
        transclude: true,
        controller: Controller
      });

  /** ngInject */
  function Controller() {
    var ctrl = this;
    ctrl.onUpdate = function(event) {
      if (event.brand) {
        ctrl.contact = event.contact
      }
    };
  }

})();

(function() {
  'use strict';

  angular
      .module('app')
      .component('contactEdit', {
        restrict: 'E',
        bindings: {
          contact: '<'
        },
        templateUrl: 'app/components/contact/contact-edit/contact-edit.html',
        transclude: true,
        controller: Controller
      });

  /** ngInject */
  function Controller() {
    var ctrl = this;
    ctrl.$onInit = function() {
      ctrl.contact = angular.copy(ctrl.contact);
    };
    ctrl.submit = function() {
      ctrl.onUpdate({
        $event: {
          contact: ctrl.contact
        }
      });
    };
  }

})();
blowsie commented 7 years ago

Found an example after all!

Short answer, apply the wire the callback bindings to the <ui-view> itself.