AngularJs CheckBox conundrum - angularjs

My view has
<input type="checkbox" class="check_box" ng-model="campaign.paused"
ng-click="CampaignPauseClicked(campaign, $event)" />
<p>campaign.paused == {{campaign.paused}}</p>
with the <p> being for debugging. It shows false, as it shoudl, given the data, but in the controller
$scope.CampaignPauseClicked = function(campaign, $event)
{
campaign.paused = ! campaign.paused;
when I breakpoint on the first code line, the value of campaign.paused is true (!).
I have searched the code and campaign.paused is not being written elsewhere.
Any idea what could be happening here?
[Update] I am using an ng-click fucntion, which I have not shown in its entirity, because I need it to "swallow" the $event and prevent it from propogating to the parent.

That's because ng-model is updating the value when you click the checkbox. You're undoing what Angular is doing for you.
If you want to do it by yourself in your $scope.CampaignPauseClicked function, remove the ng-model part from the html.
Otherwise, you can let Angular do its thing, leave the ng-model="campaign.paused" clause, and remove the first line from your ng-click callback.

Also you can replace the ng-click with the ng-change directive since you are using a checkbox.
ng-change will run everytime the checkbox state is changed (checked/unchecked)
<input type="checkbox" class="check_box" ng-model="campaign.paused"
ng-change="CampaignPauseChanged ($event)" />
<p>campaign.paused == {{campaign.paused}}</p>
And in your controller:
$scope.CampaignPauseChanged = function(event)
{
console.log(campaign.paused)
console.log(event)
}
Another option would be the ng-checked directive here is an example in this plunker. As you can clearly see the checkbox model returns true only if it is checked.

Related

checkbox with ng-change is not working with datatable and angularjs

my code is as below,
vm.dtColumns.push(DTColumnBuilder.newColumn('id').withTitle('<input name="select_all" value="1" id="example-select-all" type="checkbox" ng-change="checkedAll()" />').renderWith(actionHtml).withOption('orderable', false));
my function is as below,
$scope.checkedAll = function () {
alert();
}
but on checkbox change this function is not working
Please help me to resolve above
Might be due to the fact that you don't have an ng-model on that input.
The documentation states that ng-model has to be present for the ng-change to work.
The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.
...
Note, this directive requires ngModel to be present.

simple angular checkboxes

I have a T/F property called "valid" returning from an API call. I want to accurately display it as a checkbox, as well as allow the user to set/unset it. Setting or unsetting it will make a SAVE call.
{{vm.selectedQuestion}}
<md-checkbox
aria-label="Confirmed"
ng-model="vm.selectedQuestion.valid"
ng-click="vm.setReviewed()"
ng-checked="vm.selectedQuestion.valid">
Valid
</md-checkbox>
.
vm.setReviewed = function () {
vm.selectedQuestion.valid = !vm.selectedQuestion.valid;
// a bunch of other stuff
};
If the question gets loaded with value: true, then I see the checked box. If I uncheck the box, the valid property disappears from the object completely.
I know I'm doing something wrong with the ng-model and the ng-checked, but I've tried every combination I can think of.
Astonishingly, the angular docs and examples do not seem to address this simple case as far as I have found.
I would simply change it to:
{{vm.selectedQuestion}}
<md-checkbox
aria-label="Confirmed"
ng-model="vm.selectedQuestion.valid"
ng-change="vm.setReviewed()">
Valid
</md-checkbox>
with the function:
vm.setReviewed = function () {
// a bunch of other stuff depending on the value of vm.selectedQuestion.valid
};
Usually there is no need to over-complicate it (unless there is something about md-checkbox that I am not aware of). There is also no need to manually toggle the value in the ng-change (it's already changed by ng-model, and the value of vm.selectedQuestion.valid you see in the function is already after the change).
Here is the link for the docs of md-checkbox directive with a clear example:
https://material.angularjs.org/latest/api/directive/mdCheckbox
And the ng-change is as ng-change does, until angular goes v2, and then all bets are off. :)
A few notes on directives in question (with input from OP comment):
ng-click happens before the change of the ng-model and the checkbox in the element
ng-change happens after the change in the ng-model and the element
ng-checked is used only to set the checked attribute of the element if it's evaluated to truthy - should not be used alongside ng-model
Try following snippet
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = true;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="checkbox" ng-checked="name" ng-model="name">{{name}}</div>
</div>
</div>
Hope this will help you

NgBootbox with two way binding template not working

i have here an input button where i want to set its message using a template.At first, when i clicked the button it should run a function which will set scope.info value to info, and then the modal should popup containing the template which has the two way binding. but the binding is not working
Code:
index.html
<input
type="button"
name="name"
value="New"
ng-click="verify()"
ng-bootbox-title="Warning"
ng-bootbox-custom-dialog
ng-bootbox-custom-dialog-template="temp.html"
ng-bootbox-buttons="customDialogButtons"
ng-bootbox-class-name="some-class" />
temp.html
<div>{{info}}</div>
prog.js
$scope.verify = function(){
$scope.infos= "info";
};
SOLVED!
SOLUTION:
prog.js
$scope.verify = function(){
$rootScope.infos= "info";
};
Your code works correctly, you just miss spelled the name of your variable ({{infos}}) in your div.
JSFiddle working.
Update from comments
Try to put infos value in $rootScope instead of $scope, it seems you have an issue of accessibility.

Setting initial value of a select list generated through ng-repeat in angular

I am creating a select list from an associative array using ng-repeat.The ng-model of list is bound to a scope variable that has some initial value.The value of the options generated are the key of the array.
However, the list does not initialize with the value of the model.I thought it might have something to do with the asynchronous behaviour of ng-repeat, so i created a directive to capture the end of rendering and emit an event.This event is caught in the controller and is used to re-assign the value of the ng-model.
The event is caught correctly, but the update to the ng-model does not reflect.
If I attach a function to a button that updates the variable , it shows correctly in the list.
I know it is so because of the way ng-repeat works.How can i work around this automatically set the initial value after the list has been rendered.
Here is an example of my issue:
http://jsbin.com/gapemenova/1/edit?html,js,output
HTML:
<h1 align='center'>
{{value}}
<select ng-model='value' >
<option ng-repeat='(tid,groups) in templates' value='{{tid}}' on-last-repeat >{{tid}} </option>
</select>
<button ng-click='refresh()' >Refresh</button>
</body>
JS:
var app=angular.module('gobo',[]);
//Create A Directive To Detect The End Of ng-repeat cycle.
app.directive('onLastRepeat',function(){
return function(scope,element,attrs) {
if(scope.$last) { setTimeout(function(){
scope.$emit('onRepeatLast',element,attrs);
},10);
}
};
});
app.controller('goboCtrl',function($scope){
//Initial Value
$scope.value="2";
$scope.$on('onRepeatLast', function(scope, element, attrs){
$scope.value='3';
alert($scope.value); });
//Data Source For ng-repeat
$scope.templates={};
$scope.templates["1"]=[{"prop":"value1"}];
$scope.templates["2"]=[{"prop":"value2"}];
$scope.templates["3"]=[{"prop":"value3"}];
$scope.refresh=function(){
$scope.value="2";
};
}); //Controller ends
Check this working demo: JSBin
Simply change the option to:
<option ng-repeat='(tid,groups) in templates' value='{{tid}}'
ng-model="value" ng-selected="value === tid" on-last-repeat >{{tid}}</option>
Adding ng-model binds the selected value to $scope.value. Using ng-selected to update the selected item dynamically.
Explanations
Updating at the end of ng-repeat through $on is out of Angular $digest lifecycle, you need to run $scope.$apply to trigger a $digest cycle manually. Check JSBin
ngClick will trigger a $scope.$apply by default. Check ngClick definition in Angular 1.4.1 Line 23244:
scope.$apply(callback);
You should be using ng-options instead of using an ng-repeat to bind your options to your array. More on ng-options: https://docs.angularjs.org/api/ng/directive/ngOptions

Forms-angular, how a custom directive field can affect the $pristine state of the full record?

Question related to forms-angular project.
Preamble
The default formInput directive of forms-angular can be override by a custom directive by specifying the form.directive property in an extended mongoose model,
var CategorySchema = new Schema({
name: String,
});
var PlansSchema = new Schema({
categories: {
type: [CategorySchema],
form: {
directive: 'plan-categories'
}
}
});
The custom plan-categories directive has a template where fields of [CategorySchema] can be edited.
What is working
Let's start with a first simple template:
<div>
<div ng-repeat="category in record.categories">
<input ng-model="category.name" />
</div>
</div>
Forms-angular can successfully detect changes in these custom plan-categories directive input fields bound to data (injected scope.record). In particular when changing the user changes the value of the above input fields, the "Save" button of the page is enabled, allowing the Save operation.
The activation of the Save button thanks to the following comparison in parent formInput's BaseCtrl scope false === $scope[$scope.topLevelFormName].$pristine (see base.js).
Not working
Now, the Save button doesn't get enabled, when changing the category.name variable with an expression or a function called by ng-click, as below:
<div>
<div ng-repeat="category in record.categories">
<input ng-model="category.name" />
<button ng-click="category.name = 'Hello'">Edit</button>
</div>
</div>
On button click, the category.name variable seems to be correctly changed, since the value in the input is changed accordingly. Unfortunately, the Save button stays disabled.
Note: I also unsuccessfully tried to pass to ng-click a method (from the scope injected in the link method of the custom directive) and setting the category.name variable in a $timeout call.
I guess the ng-model directive of the input field calls parent's (multi-ancestor?) $setDirty() method.
Question
how do I magically get $setDirty() called by forms-angular in order to enable the "Save" button
If it is not possible:
how do I access BaseCtrl scope and call $setDirty() when changing the record.categories elements?
Offhand I cannot think of a magical solution, but the decidedly non-magical way is to depend on $data.baseScope (see https://github.com/forms-angular/forms-angular/blob/master/js/controllers/base.js#L12) which saves going through lots of $parents.

Resources