Unidefined variable inside the controller


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(){

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>


$scope.setCode = function(code){

Someone can help me please? Thanks!


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


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