如何以角度三次更改按钮文本?

时间:2015-01-07 12:06:44

标签: angularjs

嗨朋友们,我已经完成了按钮更改文本的代码,就像按下按钮一样,按钮的文本也会改变。但我需要再次更改按钮的文字, 例如:最初“Button1” - >(点击) - >“Button2” - >(点击) - >“Button3”。

我也需要button3。

请提示:http://jsfiddle.net/Ljrpd/17/

var app = angular.module('my-app', [], function () {

})

app.controller('AppController', function ($scope) {
$scope.toggle = true;

$scope.$watch('toggle', function(){
    $scope.toggleText = $scope.toggle ? 'Button1' : 'Button2';
})
})

有人在这个问题上帮助我。 感谢

4 个答案:

答案 0 :(得分:1)

您不需要切换变量,您可以按照Peter的建议存储选定的索引。我还会添加最后一次选择的检查:

app.controller('AppController', function ($scope) {
    $scope.buttonIndex = 0;
    $scope.buttonNames = ['Button 1', 'Button 2', 'Button 3', 'Last Button']
    $scope.changeText = function() {
        if ($scope.buttonIndex === $scope.buttonNames.length - 1) {
            $scope.buttonIndex = 0;
        } else {
            $scope.buttonIndex += 1;
        }
    };
});

JS Fiddle

答案 1 :(得分:0)

尝试我的修改:

http://jsfiddle.net/Ljrpd/18/

<button ng-click="toggle = !toggle">{{buttonNames[buttonIndex]}}</button>


var app = angular.module('my-app', [], function () {

})

app.controller('AppController', function ($scope) {
    $scope.toggle = true;
    $scope.buttonIndex = 0;
    $scope.buttonNames = ['first', 'second', 'third']

    $scope.$watch('toggle', function(){
        $scope.buttonIndex += 1;
    })
})

这是一个没有手表的版本:

http://jsfiddle.net/russf6s9/1/

<button ng-click="incrementButton()">{{buttonNames[buttonIndex]}}</button>


var app = angular.module('my-app', [], function () {

})

app.controller('AppController', function ($scope) {
    $scope.buttonIndex = 0;
    $scope.incrementButton = function() {
        $scope.buttonIndex += 1;
    }
    $scope.buttonNames = ['first', 'second', 'third']
})

答案 2 :(得分:0)

使用指令:

app.directive('changeText', function(){
  return {
    restrict: "A",
    scope: {
      changeText: "="
    },
    link: function(scope, element, attr) {
      scope.index = 0;
      element.html(scope.changeText[0]);

      element.on('click', function(){
        scope.index = (scope.index + 1) % scope.changeText.length; 
        element.html(scope.changeText[scope.index]);
      })
    }
  };
})

然后在你的html:

<body ng-controller="MainCtrl as ctrl">
  <button change-text="ctrl.textValues"></button>
</body>

Plnkr

答案 3 :(得分:0)

脚本:

.controller('myctrl', function ($scope) {
                $scope.btntext='button_1';
                $scope.changetext = function () {
                $scope.btntext = ($scope.btntext=='button_1')?'button_2':($scope.btntext=='button_2')?'button_3':'button_1';
                }
});

标记:

<input type="button" ng-click="changetext()" ng-value="btntext"/>

View in Plunker