0

I am using some checkboxes in my angular app which are checked by default.These are in ng-pristine state.How can I receive these inputs in my controller when the form is posted without making them dirty.
<input type="checkbox" name="c1" name="favoriteColors" ng-model="data.checkboxtest[1]" ng-checked="true"> <input type="checkbox" name="c2" name="favoriteColors" ng-model="data.checkboxtest[2]">

Controller:

$scope.submitNewTemplate = function(){ console.log($scope.data.checkboxtest) }

returns "undefined"

3 Answers 3

0

see i have added demo code for check box here

please have a look on it. May be this will help you

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.testModel = {
    item1: true,
    item2: false,
    item3: false
  };
  $scope.submit = function() {
    console.log($scope.testModel);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="plunker">

<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">

  <label>
    <input type="checkbox" name="test1" ng-model="testModel.item1" />Testing</label>
  <br />
  <label>
    <input type="checkbox" name="test2" ng-model="testModel.item2" />Testing 2</label>
  <br />
  <label>
    <input type="checkbox" name="test3" ng-model="testModel.item3" />Testing 3</label>
  <br />
  <input type="button" ng-click="submit()" value="Submit" />
  <pre>{{testModel|json}}</pre>
</body>

</html>

Hope this will help you a lot.

Sign up to request clarification or add additional context in comments.

Comments

0

Good question, I have never taken the time to look into this. Here is a bit of a workaround to what you want, but it does the job.

<input type="checkbox" name="c1" name="favoriteColors" ng-model="data.checkboxtest[1]" ng-init='data.checkboxtest[1] = true'>
<input type="checkbox" name="c2" name="favoriteColors" ng-model="data.checkboxtest[2]" ng-init='data.checkboxtest[2] = false'>

Here is where I found the answer How to check if any Checkbox is checked in Angular

1 Comment

thanks for the answer.but that doesn't solve my problem. actually my checkbox inputs will change dynamically through a dropdown without touching the checkboxes.
0

You can directly checked for true or false

if($scope.data.checkboxtest[1]){
  //checked
}else{
   //unchecked
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.