Science
Science

Reputation: 147

check/uncheck the check box only if the confirmation message is true in angular js

I am new in angular js. I have a check box when i click on that checkbox a confirmation message will appear. I need to to check or uncheck the check box only if i confirm the confirmation message. How can i do it with angular js.(currently the check box is check/uncheck even if i cancel the confirmation message). This is my check box element.

<input type="checkbox" 
    ng-init="checkValue = x.status" 
    ng-model="checkValue" 
    ng-true-value="1" 
    ng-false-value="0" 
    ng-checked="x.status == 1" 
    ng-click="changeStatus(<% x.id %>, 1, checkValue)">

And this is my js part

    $scope.changeStatus     = function(id, iFlag, checkValue) {    
var confrm          = confirm('Are you sure that you want to do this');
        if (confrm) {
            Data.post('url', param)
            .then(function(data){
                if (data.success == 1)
                    AlertService.setSuccess('Status changed successfully!');
                else 
                    AlertService.setError('Some error occured. Please try again');
            })
        }}

Upvotes: 1

Views: 6391

Answers (3)

byteC0de
byteC0de

Reputation: 5273

Try this, and make appropriate changes, change ng-checked value to x.status

var jimApp = angular.module("mainApp",  []);

jimApp.controller('mainCtrl', function($scope){
    $scope.status = true;
    $scope.changeStatus     = function(checkValue) {  
        var r = confirm("Are you sure that you want to do this");
        if (!r) {
            $scope.checkValue = !checkValue;
        }
      }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>

<div ng-app="mainApp" ng-controller="mainCtrl">
  {{checkValue}}
    <input type="checkbox" ng-model="checkValue" ng-checked="checkValue" ng-init="checkValue = status" ng-change="changeStatus(checkValue);">
</div>

Upvotes: 1

ravikumar533
ravikumar533

Reputation: 24

There is a syntax issue in your code. Change <%x.id%> to x.id

 <input type="checkbox" 
ng-init="checkValue = x.status" 
ng-model="checkValue" 
ng-true-value="1" 
ng-false-value="0" 
ng-checked="x.status == 1" 
ng-click="changeStatus(x.id, 1, checkValue)">

Upvotes: 0

Satish
Satish

Reputation: 56

just set ng-model value as per your logic and it should work $scope.checkValue = 1; if data.success == 1

$scope.checkValue = 0; if data.success != 1

Upvotes: 0

Related Questions