【发布时间】:2016-11-02 02:55:26
【问题描述】:
我有一个带有三个按钮的 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>
当前发生的是函数被调用,但指令没有显示/隐藏按钮点击。
【问题讨论】:
-
有什么问题。它不工作吗?任何错误
-
我没有收到任何错误。指令不会在按钮点击时显示/隐藏。
-
只是为了检查...您是否尝试将它们放入一个 div 和该 div 上的
ng-show或ng-if? -
我只是尝试将它们放在一个 div 中,并将 ng-show 直接放在 div 上,但这也不起作用。
-
PostsController在哪里获得控制权?你有ng-controller或在某处使用它的指令吗? (能否请您包含代码以显示结构)您是否尝试过使用范围检查器开发工具?
标签: angularjs angularjs-directive buttonclick