在ng-view内容的基础上显示/隐藏元素

时间:2015-11-26 08:50:32

标签: angularjs controller routing angularjs-scope ngroute

我有一个简单的div(class = blue),只有当我找到' two.html'但不是一个' one.html'或者' three.html'在ngRoute - 角度路由。有人可以为它解决问题吗?

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

有人可以帮助我在条件选择隐藏/显示我的div我的ng-view遵循的路线?

1 个答案:

答案 0 :(得分:1)

您可以在MyCntrl中使用下面给出的功能,该功能使用$location

检查其中的路径"two"
    $scope.isSecondPage = function(){
      if($location.path().search(/^\/two/) == -1)   
        return false;
      else
        return true;
};

并且可以在ng-show / ng-if中使用它,如果你想有条件地隐藏div

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