Search code examples
angularjscheckboxangularjs-scopepug

Angular checkbox loading as ng-checked='true' on ng-change not seeing the change to false


Im having an issue with my ng-repeat checkboxes. On modal load their status is set from the $http.get They load fine. but if they are set to true on load when clicked on the ng-change dosent seem to register it but when clicked again it see the change to true. this is shown in my pre and console.log()

I'll put what code I can

PUG

form.form-horizontal(name='sysInfo' ng-controller='sysInfo' ng-repeat='sysName in sysNames')
    label{{sysName.friendyName}}
        input(type='checkbox' ng-change='submit(sysName.selected, options.sysBackend, sysName.id)'  ng-model='sysName.selected' ng-checked='select.indexOf(sysName.id) != -1')

Angular

app.controller('sysInfo', sysInfo);
    function sysInfo($scope, $rootScope, $http){
    $scope.options = function(foo) {
        var config = {params :{fooName: foo}}
        $('#myModal').modal();
        $http.get('/api/boo', config)
        .then(function(resp) { 
            var selectArray = [];
            $rootScope.select = [];
            $rootScope.options = res.data.data[0];
            $rootScopesysNames = resp.data.sysInfo;
            $rootScope.sysLinks = resp.data.sysNamedLinks;
            angular.forEach(resp.data.sysNamedLinks, function(value1, key1){
                angular.forEach(resp.data.sysInfo, function(value0, key0){
                    if(value1.sysLinkId === value0.id){
                        selectArray.push(value0.id)
                        $rootScope.select = selectArray
                    }
                })
             })
        })
}

res.data.data[0] = {id:1, sysBackend:'fumanchu'} resp.data.sysInfo = [{id: 1, friendlyName:foo},{id: 2, friendlyName:fo},{id: 3, friendlyName:boo},] resp.data.sysNamedLinks = [{sysLinkId:1},{sysLinkId:2},{sysLinkId:3}]


Solution

  • this is happening because you have some conflicts between ng-model and ng-checked.

    refer the below example, the checkbox is initialized to be checked by ng-checked expression but ng-model value is false.

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <div ng-app ng-init="test=false;checked=true;">
      <input type="checkbox" ng-model="test" ng-checked="checked === true">
      {{test}}
    </div>

    In the second example, there is no confilcts and works well.

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <div ng-app ng-init="test=true;checked=true;">
      <input type="checkbox" ng-model="test" ng-checked="checked === true">
      {{test}}
    </div>