导航回来时不调用控制器

时间:2017-04-29 08:19:18

标签: javascript angularjs pug

我正在使用angularJS和Jade进行开发。我把AppController附加到我的身体标签上。每次访问新页面时,都会调用控制器。目前,我有两种不同的布局。一个有标题,导航和页脚。另一个唯一的侧边栏。当我访问第一个布局和第二个布局时,AppController调用了。但是当我从第二个布局导航到第一个布局时。不调用AppController。

index.jade

extends layout/layout
block content

Layout.jade

html
 head
  // some metas and links
 body(ng-app="myApp", ng-controller="AppController")
  div(ng-show="!profile")
   include header
   include sidemenu
   include mainmenu

  div(ng-show="profile", id="Profile", style="display:none;")
   include profile/sidemenu

  div(ng-cloak, ng-view)
     block content

  div(ng-show="!profile")
   include footer

  div(ng-show="profile", id="Profile", style="display:none")
    include profile/scripts

AppController的

// When navigating to /profile it will call the second layout
// Otherwise first layout.

if($location.path().split('/')[1] == "profile") {
    angular.element('#Profile').css('display','block');
    $scope.profile = true;
}else{
    angular.element('#Profile').css('display','none');
    $scope.profile = false;
}

问题

  

当我从第二个布局导航回第一个布局时。侧边栏(第二种布局)与第一种布局重叠。原因是未调用AppController,因此未调用css显示。

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是将控制器代码包装在函数周围,并使用ng-init指令从两个层调用该函数

$scope.cssFunc = function(){

    if($location.path().split('/')[1] == "profile") {
        angular.element('#Profile').css('display','block');
        $scope.profile = true;
    }else{
        angular.element('#Profile').css('display','none');
        $scope.profile = false;
    }

}