Search code examples
angularjs-material

changing md-selected with md-tabs and using md-button (prev, next)


I am experiencing a strange behavior when switching tabs using different methods of changing the tab index. I can change md-selected using the $scope.changeQuestion function with ng-click. I can also use the built in clicking of the md-tab to change md-selected. The issue lies when I click the md-tab and then try to click my prev or next buttons that utilize the $scope.changeQuestion function. If I click the tabs and then try to use my buttons to change the index, the buttons don't change the tab index anymore. They do log the appropriate index I want to switch to, however.

controller

$scope.changeQuestion = function(index){
     $scope.selectedQuestion = index;
};

html

<md-tabs md-selected='selectedQuestion' md-stretch-tabs md-dynamic-height md-border-bottom>
        <md-tab ng-repeat='question in assessment.questions | toArrayKeepKeys | orderBy: "order"'>
            <md-tab-label>
                {{question.order}} <i class="fas fa-fire fire" ng-if='question.bonus'></i>
            </md-tab-label>
            <md-tab-body>
                <div class='question-tab-content'>
                    <question class='margin-top-1em' details='question' answer='answers[question.key]'></question>
                    <div>
                        <md-button ng-click='changeQuestion($index - 1)' ng-hide='question.order === 1' class='md-primary md-raised no-left-margin'>Previous</md-button>
                        <md-button ng-click='changeQuestion($index + 1)' ng-hide='question.order === _.size(assessment.questions)' class='md-primary md-raised no-left-margin'>Next</md-button>
                    </div>
                </div>
            </md-tab-body>
        </md-tab>
    </md-tabs>

Here is the example of the behavior:

enter image description here

I was able to get a working example in codepen but can't seem to get it to work in my project.

Update

Tried putting a $watch on $scope.selectedQuestion and it doesn't fire if I click the tabs. It's like the md-selected='selectedQuestion' and $scope.selectedQuestion are different but only after I click a tab.


Solution

  • Found Solution: scope inheritance

    Changing $scope.selectedQuestion = 0; to $scope.selectedQuestion = { selected: 0 }; and updating other references did the trick.

    Unexplained: why the codepen example works without the modifications from the solution