根据其他事件更改ng-click的功能?

时间:2014-07-22 08:33:33

标签: javascript angularjs

我遇到了问题,我要做的是:

我有这个按钮,如果用户取消订阅,他可以点击按钮进行订阅。现在问题是,如果订阅用户,我希望他点击按钮取消订阅。

<button class="btn btn-primary subscribe-btn" ng-click="subscribe()" >
    Subscribe
</button>

我怎样才能在angularJS中做到这一点?根据用户的状态(例如:isSubscribed = true)更改按钮的功能,外观和调用功能。

2 个答案:

答案 0 :(得分:9)

试试这个:

<button class="btn btn-primary subscribe-btn" ng-click="isSubscribed ? unsubscribe() : subscribe()" >
    <span ng-show="isSubscribed">Subscribe</span><span ng-hide="isSubscribed">Unubscribe</span>
</button>

这将调用正确的函数,并显示正确的文本,具体取决于isSubscribed

但是,更清晰的选择是在控制器中处理这个问题,导致类似HTML:

<button class="btn btn-primary subscribe-btn"
        ng-controller="ButtonController"
        ng-click="toggleSubscribe()" >
    {{subscribeButton}}
</button>

只需根据用户是否订阅设置按钮的文本:

app.controller('ButtonController', ['$scope', function($scope) {
    $scope.subscribed = false;
    $scope.subscribeButton = $scope.subscribed ? 'Unsubscribe' : 'Subscribe';
    $scope.toggleSubscribe= function() {
        $scope.subscribed = !$scope.subscribed; // Handle subscription...
    };
}]);

现在,更好的方法是通过创建custom element directive

来使用模板
app.directive('subscribeButton', function() {
    return {
        templateUrl: 'subscribe-button.html'
    };
});

答案 1 :(得分:2)

您可以拥有的按钮:

<button ng-init="subscribed = true" class="btn btn-primary subscribe-btn" ng-click="changeSubscription()" >
    {{button}}
</button>

在你的app.controller中你可以拥有

$scope.changeSubscription() = function(){
    if($scope.subscribed){
        $scope.button = "subscribe";
        $scope.subscribe = false;
        unsubscribe();
    }else{
        $scope.button = "unsubscribe";
        $scope.subscribe = true;
        subscribe();
    }
}