Unidefined variable inside the controller


#1

Hi guys,

I am having some problems reading an ng-model from the controller. Perhaps is a silly error, but I don’t know.

I want to do this:

<input type="text" ng-model="code">
<button ng-click="setCode()">Login</button>

And in my controller access that variable like this:

 $scope.setCode = function(){
  	alert($scope.code);
  }

That is what I want to do but my code variable is undefined.

What I did (and works) is this:

<input type="text" ng-model="code">
<button ng-click="setCode(code)">Login</button>

And:

$scope.setCode = function(code){
  	alert(code);
  }

Someone can help me please? Thanks!


#2

The problem is with “dot notation”. When you use just $scope.code, you are using a primitive. Primitives don’t get 2 way binding.

You need to do this:

$scope.data = {};
$scope.data.code = "Something"

Update : Sorry - not sure why that code is formatting so poorly.

Definitive Source : https://github.com/angular/angular.js/wiki/Understanding-Scopes


#3

I guess that I am always going to use the “.” in my ng-models. Thanks!