2017-04-20 30 views
0

考慮以下角度1.X index.html文件:angularJS:如何conditionnaly在ng-view之外顯示一個元素?

<div ng-app="app" class="hero-unit"> 
    <a ng-show="!isHomePage" href="#!/home">Home</a> 
    <div class="container-fluid"> 
     <div ng-view></div> 
    </div> 
</div> 

我想只有當位置不在主頁上顯示的元素<a ng-show="!isHomePage" href="#!/home">Home</a>? 我應該如何繼續?我應該將這個元素映射到專用控制器上作爲mainController嗎?這是一個很好的做法嗎?

回答

1

的方式來實現這一點:

  • 您可以創建一個parent level controller(outside ng-view)在應用程序中,然後檢查當前路線並根據實施情況。

    首頁

爲了讓你可以使用當前路徑:

app.run(function ($rootScope) { 
    $rootScope.$on('$routeChangeSuccess', function (e, current, pre) { 
     console.log(current.originalPath); // Do not use $$route here it is private 
    }); 
}); 

OR

$location.path()

  • 如果您想根據視圖中的任何事件執行操作,則可以使用$scope.$emit$emit將有助於兒童與家長之間的溝通。
  • 您可以通過創建一個angular service來傳遞應用程序的當前狀態並基於該狀態實現條件。
+0

在你給的監聽器裏面,我添加了'$ rootScope.showButton = current.originalPath.indexOf(「home」)!== -1?假:真; '但在父級控制器div中,'{{showButton}}'爲空。你能用html和js給出一個完整的例子嗎? –

+0

什麼是'current.originalPath'? –

+0

我發現,這是一個模板引擎衝突!舊的應用程序原始模板引擎試圖評估花括號之間的角度表達!感謝您的回答! –

0

嘗試將ng-app移動到正文級別,然後使用$ rootScope中的服務來檢測它是否是主頁 - 我在一些應用程序中執行此操作。

例如

<body ng-app="app"> 
<div class="hero-unit"> 
<a ng-show="!NavigationService.isHomePage()" href="#!/home">Home</a> 
<input id="token" type="hidden" value="{{token}}"> 
<div class="container-fluid"> 
    <div ng-view></div> 
</div> 

在app.js

然後運行方法,設置NavigationService到rootScope,

例如

$rootScope.NavigationService = NavigationService;

0

您可以查看當前網址: 看到從這個例子: https://docs.angularjs.org/api/ngRoute/directive/ngView

<div ng-controller="MainCtrl as main"> 
    <div class="view-animate-container"> 
     <div ng-view class="view-animate"></div> 
    </div> 
    <hr /> 

    $location.path() = {{main.$location.path()}} 
    $route.current.templateUrl = {{main.$route.current.templateUrl}} 
    $route.current.params = {{main.$route.current.params}} 
    $routeParams = {{main.$routeParams}} 
</div> 
相關問題