简体   繁体   中英

ng-click with ng-checked not updating checkbox state

small question (possible a logic err), I am trying to get the checkbox to update itself automatically after clicking it and in the same time using the rest api to PUT the changes in DB, and the PUT mothod works, it updates the DB but it`s not updating the checkbox state itself only if I refresh the page, the checkbox will update.

And I have this simple code:

<input type="checkbox" ng-checked="action.state" ng-click="setState($event, key, action)"><div class="track"><div class="handle"></div></div> 

and back-end as this:

.controller('Actions', function ($scope, $filter, $resource, $ionicActionSheet, $ionicModal) {
    var actionListResource = $resource('/api/actions/');

    actionListResource.query(function (data) {
        $scope.actions = data;
    });

    $scope.setState = function (event, index, action) {

        if (action.widget === 'toggle' && action.state === 1) {
            action.state = 0;
        }
        else {
            action.state = 1;
        }

        event.preventDefault();

        var actionsResource = $resource('/api/actions/:actionId/', {actionId:'@id'}, {
            'update': {
                method: 'PUT'
            }
        }); 
    };
    ...more code here
})

action.state is always a 1 or 0 value, I've checked the $scope.actions[index].state and it`s updating itself when I click the checkbox.

Thank you!

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="myCtrl">
  <input type="checkbox" ng-model="action" ng-click="setState()">
</div>

<script>
angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.setState = function() {
      window.alert($scope.action);
      // $scope.action value will be true or false
    };
  }]);
</script>
</body>
</html>

Try ng-model instead of ng-checked. The toggle stuff looks unecessary. ng-change could also be used to trigger the request. In their docs they solve exactly the problem you describe. https://docs.angularjs.org/api/ng/directive/ngChange

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM