Robert_Junior
Robert_Junior

Reputation: 1123

Angular js model not getting updated

Am new to angular js. I have the following code

 <div ng-controller="myCtl">     

                <input type='checkbox' ng-model='selectAll'/>Select All
                <div ng-repeat="c in language.availableOptions">
                     <input type='checkbox' ng-model='language.opted[$index]' 
                     ng-checked="selectAll" ng-true-value='{{c}}'
                     ng-false-value=""/>
                     {{c}}          
                </div>         
                    {{selectAll}}
                   selected languages : {{language.opted}}    
            </div>    

   <script type="text/javascript">
    /**
     *  Module
     *
     * Description
     */
    var myApp = angular.module('myApp', []);

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

        $scope.language ={};
        $scope.language.availableOptions = ["java","c","cpp","asp"];
        $scope.language.opted=[];
        $scope.selectAll=false;

    }])


    </script>

The idea is that if user selects select all then all languages will be selected and update corresponding model [language.opted].

Now if I select 'select all' check box all checbox are selected, but the model is empty. why?

Upvotes: 0

Views: 33

Answers (1)

Fernando Pinheiro
Fernando Pinheiro

Reputation: 1816

Check the documentation for ng-checked

Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.

So, try doing this some other way.


I recommend using a ng-change in the input with a function in the controller that will set every model to the current value:

ng-change="changeSelectedValue(language.opted[$index])"

And in the controller:

$scope.changeSelectedValue = function(value){
  // Sets the value of every $scope.language.opted to "value"
}

Upvotes: 1

Related Questions