Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining ng-view="NAME" from RouteProvider

I'm really new to Angular and I have a little question about sending a template or URL into a ng-view. But the way I intend to do I may have to ng-view in my base template.

When my template base is like this:

<body>
   <div ng-view></div>
</body>

And my JS looks like:

var app = angular.module('myApp',[])
.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
    .when('/home', {
        templateUrl: '/contato'
    })
(...)

Works fine loading URL inside ng-view when I have only ONE ng-view case, HOW ABOUT IF I need to have more then one ng-view to load ? (like: ng-view="area1" and ng-view="area2")

I've tried in each $routeProvider, but won't work:

    $routeProvider
    .when('/home', {
        area1: {templateUrl: '/path1'},
        area2: {templateUrl: '/path2'}
})

How would be the right way to set each ng-view separately?

Appreciate any help! Thanks.

like image 777
Kzoty Avatar asked Oct 09 '13 01:10

Kzoty


2 Answers

Unfortunately, as you know now, you cannot have more than one ng-view on your page. You should have a look at UI-Router from AngularUI which does exactly what you are looking for (https://github.com/angular-ui/ui-router).

An example from their doc (https://github.com/angular-ui/ui-router#multiple--named-views):

setup

var myApp = angular.module('myApp', ['ui.router']);

html

<body>
    <div ui-view="viewA"></div>
    <div ui-view="viewB"></div>
    <!-- Also a way to navigate -->
    <a ui-sref="route1">Route 1</a>
    <a ui-sref="route2">Route 2</a>
</body>

template 1

<h1>State 1</h1>

template 2

<h1>State 2</h1>

js

myApp.config(function($stateProvider, $routeProvider) {

  $stateProvider
    .state('index', {
      url: "",
      views: {
        "viewA": { template: "index.viewA" },
        "viewB": { template: "index.viewB" }
      }
    })
    .state('route1', {
      url: "/route1",
      views: {
        "viewA": { templateUrl: "route1.viewA.html" },
        "viewB": { templateUrl: "route1.viewB.html" }
      }
    })
    .state('route2', {
      url: "/route2",
      views: {
        "viewA": { templateUrl: "route2.viewA.html" },
        "viewB": { templateUrl: "route2.viewB.html" }
      }
    });
});

Here you could specify a controller at the state level, that would be effective for both views, or at the view level, in order to set two different controllers.

Edit: Live demo from ui-router docs (http://plnkr.co/edit/SDOcGS?p=preview)

like image 69
jpmorin Avatar answered Oct 20 '22 19:10

jpmorin


Basically you can't have two ng-view. Have a look at this SO question:

You can have just one ng-view.

You can change its content in several ways: ng-include, ng-switch or mapping different controllers and templates through the routeProvider.

like image 23
Julian Avatar answered Oct 20 '22 20:10

Julian