Deadpool
Deadpool

Reputation: 8240

Show/Hide an element on base of ng-view content

I have a simple div (class = blue) which I want to show only if I am locating to 'two.html' but not one 'one.html' or 'three.html' in ngRoute - Routing in angular. Can someone have a solution for it?

HTML:

<html>
<head>
<!-- Start Required -->
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.1/angular-route.min.js"></script>
<script src= "angularScript.js"></script>
<!-- End Required -->
<script src= "angularScript.js"></script>
<style>
.blue {height:300px;width:300px;background:red;}
</style> 
</head>

<body ng-app="myApp" ng-controller="myCtrl"> 
<div class="blue"></div> 
Below will be the content:
<div ng-view=""></div>
<a href="#/one">One</a>
<a href="#/two">Two</a>
<a href="#/three">Three</a>
</body> 
</html>

angularScript.js

//App Declaration 
var app = angular.module('myApp', ['ngRoute'] );

//Controllers 
app.controller('myCtrl', function($scope) {});
app.controller('oneCtrl', function($scope) {});
app.controller('twoCtrl', function($scope) {});
app.controller('threeCtrl', function($scope) {});

//Routers 
app.config(function($routeProvider){

    $routeProvider
    .when('/one', {
        title: 'one',
        controller: 'oneCtrl',
        templateUrl: 'one.html'
    })  
    .when('/two', {
        title: 'two',
        controller: 'twoCtrl',
        templateUrl: 'two.html'
    })  
    .when('/three', {
        title: 'three',
        controller: 'threeCtrl',
        templateUrl: 'three.html'
    })  
    .otherwise({
        title: 'one',
        redirectTo: '/one'
    });
});

one.html

This is one

two.html

This is two

three.html

This is three

Can someone help me out in conditional selection of hide/show my div on base of route my ng-view is following?

Upvotes: 2

Views: 701

Answers (1)

Divya MV
Divya MV

Reputation: 2053

you can have a function as given below in your MyCntrl,which checks the path has "two" in it using $location

    $scope.isSecondPage = function(){
      if($location.path().search(/^\/two/) == -1)   
        return false;
      else
        return true;
};

and can use it in ng-show/ng-if in the div you want to hide conditionally.

<div class="blue" ng-show="isSecondPage()"></div> 

Upvotes: 1

Related Questions