Angularjs ng-click doesn't update view

Issue

myApp.controller( 'ModalNewInstanceCtrl', [ '$scope', '$modalInstance', function( $scope, $modalInstance ) {

$scope.tabSelected = 0;

$scope.saveFactor = function () {
    console.log('here');
    $scope.tabSelected = 0;
    console.log($scope.tabSelected);
};

That’s my controller.

    <div class="modal-header">
    <div ng-click="tabSelected = 0">Tab 1</div>
    <div ng-click="tabSelected = 1">Tab 2</div>
    <div ng-click="tabSelected = 2">Tab 3</div>

</div>
<div class="modal-body">
    <div ng-show="tabSelected == 0">
        <h3>Some content 1 here</h3>
    </div><div ng-show="tabSelected == 1">
        <h3>Some content 2 here</h3>
    </div>
    <div ng-show="tabSelected == 2">
        <h3>Some content 3 here</h3>
    </div>
</div>
<div class="modal-footer">
        <button ng-click="saveFactor()">Save and return to tab 1</button>
        <a ng-click="tabSelected = 0">Cancel and return to tab 1</a>
    </div>
</div>

And that’s my html.
I don’t know why tabSelected updates view on cancel link with ng-click="tabSelected = 0" changing directly but not inside function saveFactor(). I know that function is called properly because of console log statement. And tabSelected changed as well but not the view. I can’t $scope.$apply() inside that function because it’s give me an error.

Solution

Change your HTML to use a function when modifying scope variables
HTML:

<div class="modal-header">
<div ng-click="changeTab(0)">Tab 1</div>
<div ng-click="changeTab(1)">Tab 2</div>
<div ng-click="changeTab(2)">Tab 3</div>
...
<div class="modal-footer">
    <button ng-click="saveFactor()">Save and return to tab 1</button>
    <a ng-click="changeTab(0)">Cancel and return to tab 1</a>
</div>

JS:

$scope.tabSelected = 0;

$scope.saveFactor = function () {
    console.log('here');
    $scope.tabSelected = 0;
    console.log($scope.tabSelected);
};
$scope.changeTab= function(tabNum){
    $scope.tabSelected = tabNum;
};

Answered By – SoluableNonagon

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.