MMidia
MMidia

Reputation: 13

ng-model not changing on Controller

In my application I have a div where the content depends on the value of a radio. The value is initialised in my controller when I click on a button and it is supposed to reset when I click on him again. My problem is that after the value is initialised I can change it using the radio but It won't change when I call the function.

My html code:

<div>  
    <div ng-if="pageType=='select'">
        <label><input type="radio" ng-model="pageType" value="valueA">Value A</label>
        <label><input type="radio" ng-model="pageType" value="valueB">Value B</label>   
    </div>
    <div ng-if="pageType=='valueA'">
        <div ng-controller="valueAController">
            <div ng-include="'views/valueA.html'"></div>
        </div>   
    </div>
    <div ng-if="pageType=='valueB'">
        <div ng-controller="valueBController">
            <div ng-include="'views/value.html'"></div>
        </div>   
    </div>      
</div>

My Controller js

$scope.resetValue= function () {
    $scope.pageType= "select";
}

Any idea of what is generating this error or maybe a workaround for it?

Upvotes: 1

Views: 632

Answers (1)

Jeff Howard
Jeff Howard

Reputation: 344

The ngIf is creating an isolate scope, so it now has its own version of pageType. If you nest pageType another level on the $scope object it should work.

<div>  
    <div ng-if="pageType=='select'">
        <label><input type="radio" ng-model="magicDot.pageType" value="valueA">Value A</label>
        <label><input type="radio" ng-model="magicDot.pageType" value="valueB">Value B</label>   
    </div>
    <div ng-if="magicDot.pageType=='valueA'">
        <div ng-controller="valueAController">
            <div ng-include="'views/valueA.html'"></div>
        </div>   
    </div>
    <div ng-if="magicDot.pageType=='valueB'">
        <div ng-controller="valueBController">
            <div ng-include="'views/value.html'"></div>
        </div>   
    </div>      
</div>

In your controller

$scope.resetValue= function () {
    $scope.magicDot = {
      pageType: "select"
    };
}

Upvotes: 1

Related Questions