AngularJS ng-click和ng-view没有响应

时间:2014-03-30 01:10:27

标签: angularjs

我正在使用ng-show和ng-click来显示/隐藏2个div,具体取决于用户点击其中一个应用菜单,如下所示。我面临的问题是,点击链接显示仪表板div没有显示任何内容,而是显示另一个div(div2)。有人可以检查我的代码,让我知道我在这里做错了什么?感谢

索引

<div id="header" ng-controller="MenuController">
        <ul >
          <li>
            <a href="#/">Main</a>
          </li>
          <li>
               <a href ng-hide="userLogged == 1">Login</a>
               <a href ng-click="switchDashboard()" ng-show="userLogged > 1">Dashboard</a>
          </li>
        </ul>
</div>   
<div>
  <div ng-controller="MenuController">

    <div id="dashboard" ng-show="showUserPanel">
            <ul>
                <li><a href="/">Menu item 1</a></li>
                <li><a href="/">Menu item 2</a></li>
            </ul>
    </div>

    <div id="div2" ng-hide="showUserPanel">
            <ul>
                <li><a href="/">Reg item 1</a></li>
                <li><a href="/">Reg item 2</a></li>
            </ul>          
    </div>

    <div ng-view></div>

  </div>
</div>      

MenuController:

        $scope.showUserPanel = false;

        $scope.switchDashboard = function(){
            $scope.showUserPanel = !$scope.showUserPanel;
        };

我也尝试将索引更改为只有一个MenuController实例,但我仍然有如下所示的相同问题

<div id="header" ng-controller="MenuController">
        <ul >
          <li>
            <a href="#/">Main</a>
          </li>
          <li>
               <a href ng-hide="userLogged == 1">Login</a>
               <a href ng-click="switchDashboard()" ng-show="userLogged > 1">Dashboard</a>
          </li>
        </ul>

    <div id="dashboard" ng-show="showUserPanel">
            <ul>
                <li><a href="/">Menu item 1</a></li>
                <li><a href="/">Menu item 2</a></li>
            </ul>
    </div>

    <div id="div2" ng-hide="showUserPanel">
            <ul>
                <li><a href="/">Reg item 1</a></li>
                <li><a href="/">Reg item 2</a></li>
            </ul>          
    </div>

</div>   
<div>
  <div ng-controller="MenuController">

    <div ng-view></div>

  </div>
</div>      

2 个答案:

答案 0 :(得分:1)

你有两个不同的控制器实例,它们将彼此独立运作,请看这个小提琴:http://jsfiddle.net/k4YH6/

HTML:

<div ng-app>
    <div ng-controller="MyCtrl">
        <button type="button" ng-click="increment()">Ctrl instance 1: {{value}}</button>
    </div>
    <div ng-controller="MyCtrl">
        <button type="button" ng-click="increment()">Ctrl instance 2: {{value}}</button>
    </div>
</div>

JS:

function MyCtrl($scope) {
    $scope.value = 1;
    $scope.increment = function () {
        $scope.value++;
    };
}

更相关的小提琴:http://jsfiddle.net/jph4n/

答案 1 :(得分:0)

您不需要switchDashoard()函数。

ng-click="showUserPanel = !showUserPanel"
ng-show="showUserPanel"

showUserPanel = !showUserPanel将切换ng-show / ng-hide的值。