Hiero
Hiero

Reputation: 2205

AngularJS nested controllers

I have an AngularJS app with 2 routes /home and /about.

I'm using ng-router and each route has different controllers HomeCtrl and AboutCtrl. The default route is /home.

The thing is that before display the content I want to add a preloader, just a simple div which will hide when the content is loaded.

  <div class="myApp">

    <div class="preloader"></div>

    <div ui-view></div>    

  </div>

My question is, in which controller should I add this? Should I add a new controller outside the ng-view for this kind of stuff?

Can someone explain me best practice?

Upvotes: 0

Views: 63

Answers (3)

Boris Parnikel
Boris Parnikel

Reputation: 863

@Hiero In your case of course, you have to create new controller.

Also you can use nested views. Something like this:

$stateProvider.state('home', {
        url: '/home',
        views: {
            "main": {
                templateUrl: '....',
                controller: '....'
            },
            'view-with-data@home': {
                templateUrl: '...',
                controller: '...',
            }
        }
    });

See more at https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views

Upvotes: 0

asdf_enel_hak
asdf_enel_hak

Reputation: 7650

You have ng-view, and your views render over there with its corresponding controller.

So the only thing you need ng-if

<ng-view>
  <div ng-if="!$scope.contentIsReady">
         content loading
  </div>
  <div ng-if="$scope.contentIsReady">
          content here
  </div>
</ng-view>

Upvotes: 1

Boris Parnikel
Boris Parnikel

Reputation: 863

I suppose the best way to do this is to use flag for data loaded indication directle in controller. So depend on this flag with ng-if directive you can show 'div' with loading indicator if dataLoadedFlag is false and div with your data otherwise.

Upvotes: 1

Related Questions