AngularJS flag model value undefined

I have a problem when I try to publish the flag value in my model on the server, and since the flag was not associated with the form, angular did not seem to assign a value to it, when I request the flag value, it returns as undefined.

Here is my markup:

<div class="form-group"> <input id="templateDisable" type="checkbox" ng-model="template.disabled" /> <label for="templateDisable">Disabled</label> </div> 

And here is the version of my save action on my controller:

 $scope.save = function (form) { if (form.$valid) { var formData = new FormData(); // this is the problem line of code formData.append("disabled", $scope.template.disabled); // ... some other stuff } }; 

Actually, checking off and then unchecking the box before I click on the save result will cause the template.disabled property to be false, which I expected without manual intervention.

I saw other related questions, for example. AngularJS: The initial value of the flag is not in the model , but is it necessary, like a simple flag, to bake? I did not need to write directives for managing flags?

+7
javascript angularjs checkbox
source share
2 answers

This is for the design. If you need a default value for your model, you should initialize it inside the controller (recommended) or use ng-init .

 app.controller('AppController', [ '$scope', function($scope) { $scope.template = { disabled = false }; } ] ); 
 <div class="form-group"> <input type="checkbox" ng-model="template.disabled" ng-init="template.disabled=false" /> <label>Disabled</label> </div> 
+9
source share

When a page is loaded (or updated), the status is "unverified". In other words, it will overwrite the user's actual selection whenever the page is refreshed.

 <input type="checkbox" ng-model="template.disabled" ng-init="template.disabled=false" /> 

If, however, you want the state of the flag to be set to the default state initially and you also want it to remember user interactions, then you need the following.

 <input type="checkbox" ng-model="template.disabled" ng-init="template.disabled = template.disabled || false" /> 
+6
source share

All Articles