Two views in one AngularUI Router state sharing scope

前端 未结 2 1359
野的像风
野的像风 2020-12-03 08:01

I am pretty new to the AngularUI Router and would like the use it for the following scenario:

The layout common to all pages includes a top navbar c

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 08:28

    $scope is not the model, its a reference to a model, glue in between the data & the view. If $scopes in two, or more, controllers need to share one model/state/data use a singleton object instance by registering a angular service. That one service/factory can be injected into as many controllers as you like, and then everything can work off that one source of truth.

    Heres a demo of 1 factory linking $scopes in navbar & body with ui-router http://plnkr.co/edit/P2UudS?p=preview (left tab only)

    ui-router (viewC is navbar):

    $stateProvider
    .state('left', {
      url: "/",
      views: {
        "viewA": {
          controller: 'LeftTabACtrl',
          template: 'Left Tab, index.viewA 
    ' + '' + '
    selected2.data: {{selected2.data}}
    ' }, {...}, "viewC": { controller: 'NavbarCtrl', template: 'Left Tab, index.viewC
    ' + '' + '
    selected.data: {{selected.data}}
    ' } } })

    Factory & Controllers:

    app.factory('uiFieldState', function () {
        return {uiObject: {data: null}}
    });
    
    app.controller('NavbarCtrl', ['$scope', 'uiFieldState', '$stateParams', '$state',
        function($scope, uiFieldState, $stateParams, $state) {
            $scope.selected = uiFieldState.uiObject;
        }
    ]);
    
    app.controller('LeftTabACtrl', ['$scope', 'uiFieldState', '$stateParams', '$state',
        function($scope, uiFieldState, $stateParams, $state) {
            $scope.selected2 = uiFieldState.uiObject;
        }
    ]);
    

    As you can see, the factory object {uiObject: {data: null}} is injected into the controller with uiFieldState & then its simply $scope.selected = uiFieldState.uiObject; for connecting the factory to the scope ng-model="selected.data" .`

提交回复
热议问题