Narendra Singh Rathore
Narendra Singh Rathore

Reputation: 706

Getting $scope variable undefined in angularjs

When i initialize the $scope.s with some value it's working properly. But when it's not initialize with any value as shown below, it generates error in console saying $scope.s undefined on click event bind with button

 var mainApp = angular.module('mainApp', ['ngRoute']);
mainApp.controller('homeCtrl', ['$scope', '$http', function ($scope, $http) {


$scope.title = 'Home page';
$scope.s = '';
$scope.m = '';
$scope.subscribe = function () {


    console.log($scope.s); // undefined


}
}]);

<div data-ng-app="mainApp" data-ng-controller="homeCtrl">
<div>
    <h1>{{title}}</h1>
</div>
<div>
    <h3>Want to become a seller and earn more..?</h3>
    <p>Add your email and we will get in touch.</p>
    <div>
        <input type="email" data-ng-model="s" id="txtEmail" />
    </div>
    <div>
        <div>                
            <button data-ng-click="subscribe();">Send</button>
        </div>            
    </div>
</div>
<div>
    {{m}}
</div>

Upvotes: 0

Views: 723

Answers (1)

tylerwal
tylerwal

Reputation: 1870

The $scope.svariable is undefined because you are using input of type email and having the value a non-valid email.

This 'feature' doesn't seem to be well documented, but the example at angular's documentation for input[email] clearly shows the same behavior: input[email] @ docs.angularjs.org; try an valid and an invalid email address in their example and you're see the same behavior as you are witnessing.

So your options are: switch to input of type text or plan on your model being undefined unless the email is valid.

Here is issue within angularjs's github that goes back to 2012 with the same behavior:

Binding doesn't work with input type="email"

Upvotes: 3

Related Questions