Saturday, May 2, 2015

AngularJS ui-router nested states Hint

The cool thing about nested states in ui-router is we can define a resolve property to materialize any data (say from a service) in the parent state, and this data is now available to all the children states! Very cool, as this allows data to be shared across different states - read different views - without fetching them again and again and retaining context. Note that a single controller can be used to serve all the states within a nested states hierarchy.

Example code below. The coupon data from the parent state is available across all nested views!

.state("couponEditParent", {
                abstract: true,
                 url: "/coupons/edit/:couponId",
                 templateUrl: "app/coupons/couponEditView.html",
                 controller: "CouponEditCtrl as vm",
                 resolve: {
                       couponService: "CouponService",
                       coupon: function(couponService, $stateParams) {
                                           var couponId = $stateParams.productId;
                                           return couponService.get({couponId: couponId})
                                    }
                       }
  })
.state("couponEditParent.basicInfoChild", {
                 url: "/basicInfoChild",
                 templateUrl: "app/coupons/couponEditBasicInfoView.html"
  })
.state("couponEditParent.detailsInfoChild", {
                 url: "/detailsInfoChild",
                 templateUrl: "app/coupons/couponEditDetailsInfoView.html"
  })

Note that if your app does not require activating the Parent state alone (without activating a child state), ui-router provides a property called "Abstract State" that can be applied to the parent state, so it can never be explicitly activated. Activation attempt will throw an exception! It is only activated implicitly when one of the child states is activated.

No comments:

Post a Comment