Search code examples
angularjsngrouteangularjs-ng-href

Unable to change ng-href onClick event


I have a footer with a button in my angular app. The button has an ng-href attribute which should change during the ng-click event to affect the routing mechanism. For some reason I cant make this work. The ultimate goal is to append numbers, 1 to five each button click.

The footer is a component:

app.component('footerx', {
    bindings: {

    },
    templateUrl: 'views/footer.html',
    controller: function () {
        this.buttonText = "Next";
        var self = this;
        var i = 1;
        this.changeHref= function () {
            self.questionIndex=i;
            i++;
        }
    }
});

Footer HTML:

<footer class="footer">
    <div class="container">
        <a class="btn btn-primary" ng-click="$ctrl.changeHref()" ng-href="#/quiz/{{questionIndex}}" id="btn">{{$ctrl.buttonText}}</a>
    </div>
</footer>

Routing JS part:

...
        .when("/quiz/:index", {
            templateUrl: "views/questionPage.html",
            controller: "questionController"
        })
...

EDIT: Right now the url does not fully change. This means it does not have the questionIndex. It looks like this:

http://localhost/myApp/#/quiz/

Solution

  • Use "#/quiz/{{$ctrl.questionIndex}}

    <footer class="footer">
        <div class="container">
            <!-- REMOVE
            <a class="btn btn-primary" ng-click="$ctrl.changeHref()" 
                      ng-href="#/quiz/{{questionIndex}}" id="btn"> 
               {{$ctrl.buttonText}}
            </a>
            -->
            <!--ADD -->
            <a class="btn btn-primary" ng-click="$ctrl.changeHref()" 
                      ng-href="#/quiz/{{$ctrl.questionIndex}}" id="btn"> 
               {{$ctrl.buttonText}}
           </a>
        </div>
    </footer>