按钮上显示/隐藏角度指令单击

时间:2016-11-02 02:55:27

标签: angularjs angularjs-directive buttonclick

我有一个带有三个按钮的HTML页面。我也有两个Angular指令。我想要完成的是当点击按钮a时,我希望指令1显示,指令2隐藏。单击按钮2时,我希望指令1隐藏,指令2显示。这是我的指示:

.directive('topPosts', function () {
   return {
     restrict: 'E',
     templateUrl: 'topPosts.html',
     controller: 'PostsController'
   }
 });

.directive('otherPosts', function () {
    return {
      restrict: 'E',
      templateUrl: 'otherPosts.html',
      controller: 'PostsController'
    }
  });

这是我的控制器:

.controller('PostsController', ['$scope', 'PostsFactory', function($scope, PostsFactory) {

    $scope.posts = [];
    $scope.showTopPosts = true;
    $scope.showOtherPosts = false;

    $scope.topPosts = function() {
      $scope.showTopPosts = true;
      $scope.showOtherPosts = false;
    };

    $scope.otherPosts = function() {
      $scope.showTopPosts = false;
      $scope.showOtherPosts = true;
    };

    $scope.areTopPosts = function(posts) {
      return posts.privacy === 'public' && posts.comments > 10 && posts.views > 9000 && posts.title.length < 40;
    };

    $scope.areOtherPosts = function(posts) {
      return posts.comments <= 10 && posts.views <= 9000 && posts.title.length >= 40;
    };

    var init = function() {
      PostsFactory.getPosts.success(function(data) {
        $scope.posts = data;
      });
    };

    init();
  }]);

这是我的部分,它包含两个指令:

<div class="container">
  <top-posts ng-show='showTopPosts'></top-posts>
  <other-posts ng-show='showOtherPosts'></other-posts>
</div>

这是我的index.html:

<body ng-controller='PostsController'>
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">
  <div class="container-fluid">
  <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <a class="navbar-brand" href="/main"></a>
    </div> <!-- END NAVBAR-HEADER -->
  </div> <!-- END CONTAINER-FLUID -->
</nav>

<div class="container">
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-default" ng-click="topPosts()">Top Posts</button>
    <button type="button" class="btn btn-default" ng-click="otherPosts()">Other Posts</button>
    <!-- <button type="button" class="btn btn-default" ng-click="dailyTopPost()">Daily Top Post</button> -->
  </div>
</div>

<div ng-view class='slide-animation'></div>

当前正在发生的事情是调用函数,但指令没有显示/隐藏在按钮点击上。

2 个答案:

答案 0 :(得分:0)

我将工作代码放在codepen中,似乎工作得很好http://codepen.io/arthur_souviron/pen/pEMMaJ/

我认为您的问题来自您存储的方式$scope.showTopPosts$scope.showOtherPosts。尝试将它们存储在对象中,而不是直接在$scope

下设置它们

例如: $scope.data = { showTopPosts: true, showTopPosts: false }

并在您的模板中:<top-posts ng-show="data.showTopPosts"></top-posts>

答案 1 :(得分:0)

只需在指令前添加div:

<div class="container">
  <div ng-show='showTopPosts'><top-posts ></top-posts></div>
  <div ng-show='showOtherPosts'><other-posts ></other-posts></div>
</div>