How do I share $scope data between states in angularjs ui-router?

后端 未结 5 2006
执笔经年
执笔经年 2020-11-22 07:23

Without using a service or constructing watchers in the parent controller, how would one give children states access to the main controller\'s $scope.

5条回答
  •  渐次进展
    2020-11-22 08:04

    You can get the whole scope through $rootScope. If you need just part of the scope, ui-router has a custom data feature.

    Here's how to do a multi-step form. I needed the routes to contain info for about their steps in the flow.

    First, I have some routes with UI-router:

      // Sign UP routes
      .state('sign-up', {
        abstract: true,
        url: '/sign-up',
        controller: 'SignupController',
        templateUrl: 'sign-up/index.html',
      })
      .state('sign-up.start', {
        url: '-start',
        templateUrl: 'sign-up/sign-up.start.html',
        data: { step: 0, title: 'Welcome to Mars!', },
      })
      .state('sign-up.expertise', {
        url: '-expertise',
        templateUrl: 'sign-up/sign-up.expertise.html',
        data: { step: 1, title: 'Your Expertise'},
      })
    

    Notice:

    • the data element in each route.
    • The abstract state has SignupController. That's the only controller for this multi-step form. The abstract isn't required, but makes sense for this use case.

    SignupController.js

    angular.module('app').controller('SignupController', function($scope, $state) {
      $scope.state = $state;
    });
    

    Here we get ui-router's $state and put it on $scope

    Here is the main template 'sign-up/index.html',:

    {{state.current.data.title}}

    This is a multi-step-progress control {{state.current.data.step}}

    The child templates can be whatever they like.

提交回复
热议问题