How do I get an input value into Angular's $scope?

Arhyaa picture Arhyaa · Jun 1, 2015 · Viewed 47.3k times · Source

I'm new to Angular, and I am trying to do something really basic. Here is a part of a view (all angular files are added elsewhere) :

 <div ng-controller='ctrl'>
    <input type='text' ng-model='id'>
 </div>

And here is my controller :

 module.controller('ctrl',['$scope', function ($scope) {

    // get the scope value here
}]);

What I'm trying to do is really simple. I'd like to use the input value. I tried something like $scope.data = [] and $scope.data.push($scope.id) to create an array with the scope's value, but it didn't work. When I tried to display the value, I got an 'undefined' on the console.

Do you guys have any idea ?

Edit : The view also has a button with the ng-click directive which trigger the controller's function where I try to get my value.

Answer

Tom picture Tom · Jun 1, 2015

The value will automatically be added to the $scope, but you have to type something into the input element.

That said, you need to trigger something to get this value. For example, where you have your comment // get the scope value here -- this is triggered as soon as the controller is initialized and never called again; so, it's going to log undefined at that time. However, if you set it to a button click, or something, you will see it's available:

<div ng-controller='ctrl'>
   <input type='text' ng-model='id'>
   <button ng-click="logId()">Log ID</button>
</div>

And your controller:

module.controller('ctrl',['$scope', function ($scope) {
    $scope.logId = function() {
        console.log($scope.id);
    }
}]);

Now type something into the input and click the button.