Cazs
Cazs

Reputation: 21

Angularjs how can add condition in $routeProvider?

I have this code for wordpress:

1-Page : http://localhost/contact/
2- Post : http://localhost/hello-world/

var app = angular.module('localhost', ['ngRoute','ngSanitize','ngResource']);
app.config(function($routeProvider, $locationProvider,$controllerProvider) {
    $locationProvider.html5Mode(true);
    $controllerProvider.allowGlobals();
    $routeProvider
    .when('/:slug/', {
        templateUrl: localiceTemplates.partials + 'page.html',
        controller: getPages
    })

        .when('/:slug/', {
        templateUrl: localiceTemplates.partials + 'post.html',
        controller: getPost
    });

As you see I'm using "when" for identic slug. But when I try to treat one has the category pages and the other post. I was trying to do something like the following

    $routeProvider
.when('/:slug/', {
    if(":category"=="pages"{
        templateUrl: localiceTemplates.partials + 'page.html',
        controller: getPages
    })
}else{
    templateUrl: localiceTemplates.partials + 'post.html',
    controller: getPost
}

Upvotes: 0

Views: 573

Answers (1)

passerby
passerby

Reputation: 1862

I've been faced with the same issue that permalinks in Wordpress to pages and posts have the same structure: '/:slug/'.

I've found two alternatives. They do not address an extra condition, but solves the issue of identical permalinks for pages and posts.

Alternative 1:

You can change how permalinks are generated for posts to (for example) "/posts/%postname%/". Only blog posts are redirected to this new permalink. Pages are not affected.

Now you can discriminate between page and post slugs by using '/:slug/' resp. '/posts/:slug/'.

    $routeProvider
   .when('/blog/:slug/', {
        templateUrl: 'wp-content/themes/mytheme/post.html',
        controller: 'Posts'
    })
    .when('/:slug/', {
        templateUrl:'wp-content/themes/mytheme/page.html',
        controller: 'Page'
    })

Alternative 2:

You can use a wp-json request that search for a slug in both pages and posts. Use the "type" parameter for this.

$http.get('wp-json/posts?type[]=post&type[]=page&filter[name]=' + $routeParams.slug)
    .success( function ( data, status, headers, config ) {
        $scope.posts = data;
    } )
    .error( function ( data, status, headers, config ) {
        console.log( "error" );
    } );

In a template you can use a ngIf or ngSwitch to test for the "post.type" value and include different templates to display post or page data.

<div ng-repeat="post in posts">
    <div ng-switch on="post.type">
        <div ng-switch-when="page">
            <div ng-include="'wp-content/themes/mytheme/page.html'"></div>
        </div>
        <div ng-switch-when="post">
            <div ng-include="'wp-content/themes/mytheme/post.html'"></div>
        </div>
    </div>
</div>

Upvotes: 1

Related Questions