Jamesla
Jamesla

Reputation: 1408

Unchecking an angular bound checkbox programmatically

I'm trying to uncheck a checkbox bound using ng-model to a scope variable. Basically the below doesn't uncheck after 2 seconds.

html

<div ng-controller="AppCtrl">
    <input type="checkbox" ng-model="checked">
</div>

js

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

function AppCtrl($scope) {
    $scope.checked = true;

    setTimeout(function(){
        $scope.checked = false;
        alert('should be unchecked!');
    },2000);
}

https://jsfiddle.net/thomporter/tcVhN/

Upvotes: 2

Views: 1736

Answers (3)

Eduardo Steffens
Eduardo Steffens

Reputation: 133

This work fine for me!

HTML FILE

<input type="checkbox" [(ngModel)]="checked" [checked]="checked" (change)="onChange(checked? 'block':'none')">

.TS FILE

export class TopBarComponent implements OnInit {

  checked: boolean;

  constructor(public dados: DadosService) { }


  ngOnInit() {
    if(this.dados.meusChamados == 'block')
    this.checked = true;
    else
    this.checked = false;
  }


  onChange(event : any){
    this.dados.meusChamados = event;
  }



}

checked = variable created on .ts file

onChange = a function created on .ts file to change the status of a div to display: none|block

Upvotes: 1

jrkt
jrkt

Reputation: 2715

You need to set your checked variable to the selected attribute.

<div ng-controller="AppCtrl">
    <input type="checkbox" selected="{{checked}}">
</div>

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try to use angular $timeout service instead of javascript's setTimeout

Becuase if you use setTimeout in angularjs you need use $scope.$apply() to ensure the changes in scope. check this fiddle

But $timeout will do this work for you.

Like this

$timeout(function(){
    $scope.checked = false;
    alert('should be unchecked!');
},2000);

JSFIDDLE

Upvotes: 4

Related Questions