AngularJS ng-click无法使用$ scope变量

时间:2016-12-10 08:50:13

标签: javascript angularjs angularjs-scope ng-show angularjs-ng-show

无法让我的底部div显示出来。

从今年开始尝试SO中的所有建议。在$ scope中添加了一个变量,尝试了$ scope.apply();等等。

<nav class="navbar navbar-default navbar-fixed-top" role="navigation" ng-controller="navController">
    <div class="navbar-header" >
      <button type="button" class="navbar-toggle pull-left" data-toggle="collapse" data-target=".navbar-collapse" ng-click="navCollapse()">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/#!/">Exampe</a>
    </div>
    <div class="cart-summary">
        <a href="/#!/cart">
          <image src="/example/source" />
            <div class="cart-info">
              <div class="item-count"><p>{{ ngCart.getTotalItems() }} <ng-pluralize count="ngCart.getTotalItems()" when="{1: 'item', 'other':'items'}"></ng-pluralize><p></div>
              <div class="total-cost"><p>{{ ngCart.totalCost() | currency }}<p></div>
            </div>
          </a>
    </div>
</nav>
<div ng-show="vm.open" class="half-menu" id="side-menu" >
  <ul>
      <li><button><a href="/#!/cart">Cart</a></button></li>
  </ul>
</div>

在我的navController中:

console.log('navController up!');
$scope.vm = { open: false};
$scope.navCollapse = function(){
  console.log('before click', $scope.vm.open);
  $scope.vm.open = !$scope.vm.open;
//  $scope.vm.open = ($scope.vm.open == false) ? true : false;
  console.log('after click', $scope.vm.open);
  //open up menu
};

我知道控制器已加载,因为控制台日志会显示出来。

1 个答案:

答案 0 :(得分:0)

你的div似乎超出了控制器的范围。尝试将整个事物包装在另一个div中,如下所示:

    <div ng-controller="navController">
    <nav class="navbar navbar-default navbar-fixed-top" role="navigation" >
    <div class="navbar-header" >
      <button type="button" class="navbar-toggle pull-left" data-toggle="collapse" data-target=".navbar-collapse" ng-click="navCollapse()">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/#!/">Exampe</a>
    </div>
    <div class="cart-summary">
        <a href="/#!/cart">
          <image src="/example/source" />
            <div class="cart-info">
              <div class="item-count"><p>{{ ngCart.getTotalItems() }} <ng-pluralize count="ngCart.getTotalItems()" when="{1: 'item', 'other':'items'}"></ng-pluralize><p></div>
              <div class="total-cost"><p>{{ ngCart.totalCost() | currency }}<p></div>
            </div>
          </a>
    </div>
</nav>
<div ng-show="vm.open" class="half-menu" id="side-menu" >
  <ul>
      <li><button><a href="/#!/cart">Cart</a></button></li>
  </ul>
</div>
</div>

Ofc,有时将菜单控制的导航菜单和组件放入单个包装器中是不可取的。在这种情况下,您可以使用services和$ broadcast / $ emit来传达更改。

https://plnkr.co/edit/xwQkUYrDu9WL9dC46MOY?p=preview