如何隐藏单击按钮1并显示button2,然后单击button2隐藏button2并在angularjs中显示button1?

时间:2014-09-19 08:22:04

标签: javascript angularjs-directive

当用户点击button1并显示button2时,我试图隐藏button1。当用户点击button2并显示button1时。当用户点击button1时调用函数myController1,当用户点击button2时调用函数myController2

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-controller="myController">

<button ng-click="test1=true;myController1()" ng-show="test1">button1</button>

<button ng-show="test2" ng-click="test1=true;myController2()">button2</button>

</div>
<script>
function myController1() {
    alert("hello");
}
function myController2() {
    alert("hiii");
}
</script> 

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> 

</body>
</html>

如何显示其他元素并调用控制器

4 个答案:

答案 0 :(得分:0)

显示按钮1的变量= true,并显示按钮2的变量= false。

<button ng-click="toggleButtons()" ng-show="showButton1">button1</button>

<button ng-click="toggleButtons()" ng-show="!showButton1">button2</button>

然后在你的控制器中

$scope.showButton1 = true;

$scope.toggleButtons = function () {
  $scope.showButton1 = !$scope.showButton1;
};

或者(取决于你需要这个的原因)你可以通过将它绑定到你点击时改变的变量来改变按钮中的文本。

<button ng-click="toggleButtons()" ng-show="showButton1">{{buttonText}}</button>

答案 1 :(得分:0)

如果你只使用一个变量来控制显示/隐藏,你可以减少突兀和代码更清晰。

<button ng-click="click1()" ng-show="button==1">button1</button>
<button ng-click="click2()" ng-show="button==2">button2</button>

控制器:

$scope.button = 1;
$scope.click1 = function() {
    alert(1);
    $scope.button = 2;
};
$scope.click2 = function() {
    alert(2);
    $scope.button = 1;
};

演示:http://plnkr.co/edit/uZNwVDFWZyYvLFh2KgSQ?p=preview

答案 2 :(得分:0)

您应该在相应的控制器中定义这些功能。你提到了ng-controller,在myController中定义那些函数。

参见示例

xxxx.controller('myController', function($scope) {
    $scope.myController1 = function() {
        alert("hello");
    }
    $scope.myController2 = function() {
        alert("hiiii");
    }
});

答案 3 :(得分:0)

<div ng-app="app" ng-controller="demo">
  <button ng-click='btn1();' ng-show="show_btn1">btn1</button>
  <button ng-click='btn2();' ng-show="show_btn2">btn2</button>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> 
<script>
angular.module('app', []).controller('demo', function demo($scope) {
  $scope.show_btn1 = true;
  $scope.show_btn2 = false;

  $scope.btn1 = function() {
    $scope.show_btn1 = false;
    $scope.show_btn2 = true;
  };

  $scope.btn2 = function() {
    $scope.show_btn1 = true;
    $scope.show_btn2 = false;
  };
})
</script>