seus
seus

Reputation: 568

AngularJS Printing text if checkbox is checked

I am trying to print text on the page in a <h1> tag depending on whether a check box is checked or not.

$scope.EmailMe = function(email) {
    if($scope.emailchecked == 1) {
        $scope.test = "emailSent";
    } else {
        $scope.test = "nothing";
    }
    }

HTML is :

        <input type="checkbox" ng-model="emailchecked" ng-change="EmailMe(1)">
        <h1> @{{test}} </h1>

I have the text printing but the checkbox is not being checked. or allowing for change please help :)

Upvotes: 1

Views: 1173

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Use ng-true-value & ng-false-value, so that will give you 1/0 value based on selection.

<input type="checkbox" ng-model="emailchecked"
  ng-true-value="1" 
  ng-false-value="0" 
  ng-change="EmailMe(emailchecked)">

Demo Plunkr

Even if you don't use ng-true-value, but that would not kept you model value to 0/1. By default checkbox value is true/false.

Upvotes: 1

Sagar
Sagar

Reputation: 106

You need to change if(email = 1) to if(email == 1). One equal is missing

Upvotes: 0

sreeramu
sreeramu

Reputation: 1223

HTML

  <body ng-controller="MainCtrl">
    <input type="checkbox" ng-model="emailchecked" ng-change="EmailMe()">
    <h1> @{{test}} </h1>
  </body>

Controller

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.EmailMe = function() {
    if($scope.emailchecked == 1) {
        $scope.test = "emailSent";
    } else {
        $scope.test = "nothing";
    }

    };

});

http://plnkr.co/edit/EfIMMn7Be7QL258aUiXW

and in your code you are changing the emailchecked which is not required.

Upvotes: 1

Related Questions