javascript - Switch multiple classes and vars with ng-click -
this first attempt doing pagination links angular.
<div ng-init="page1 = true" ng-show="page1"></div> <div ng-show="page2"></div> <div ng-show="page3"></div> <div> <div class="btn-group" role="group"> <button ng-click="page1 = true; page2 = false; page3 = false" ng-class="page1 ? 'btn btn-info' : 'btn btn-default'">1</button> <button ng-click="page2 = true; page1 = false; page3 = false" ng-class="page2 ? 'btn btn-info' : 'btn btn-default'">2</button> <button ng-click="page3 = true; page1 = false; page2 = false" ng-class="page3 ? 'btn btn-info' : 'btn btn-default'">3</button> </div> </div>
for moment when click button page2, i'm manually making buttons page1 , page3 switch classes through setting page1 , page3 vars false.
is there way, when clicking page2 button, make other similar buttons dynamically switch classes , set vars false out of scope of element being clicked?
instead of defining multiple vars such page1, page2, page3 create 2 methods on $scope:
var active = 1; // default active page $scope.activate = function(page) { active = page; } $scope.isactive = function(page) { return page === active; };
then template like:
<div ng-show="isactive(1)"></div> <div ng-show="isactive(2)"></div> <div ng-show="isactive(3)"></div> <div> <div class="btn-group" role="group"> <button ng-click="activate(1)" ng-class="isactive(1) ? 'btn btn-info' : 'btn btn-default'">1</button> <button ng-click="activate(2)" ng-class="isactive(2) ? 'btn btn-info' : 'btn btn-default'">2</button> <button ng-click="activate(3)" ng-class="isactive(3) ? 'btn btn-info' : 'btn btn-default'">3</button> </div> </div>
later on might in template make more dynamic:
<div ng-repeat="page in pages" ng-show="isactive(page.index)"></div> <div> <div class="btn-group" role="group"> <button ng-repeat ng-click="activate(page.index)" ng-class="isactive(page.index) ? 'btn btn-info' : 'btn btn-default'">{{page.index}}</button> </div> </div>
note: dynamic example assuming property on $scope looks similar this:
$scope.pages = [ {index: 1}, {index: 2}, {index: 3} ];
you'll find more info on ngrepeat on page: https://docs.angularjs.org/api/ng/directive/ngrepeat
Comments
Post a Comment