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

2019-02-16 19:12发布

问题:

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.

回答1:

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.



回答2:

If you really need it in array, just do this in your controller:

$scope.data = [0];

and in HTML do <input type="text" ng-model="data[0]">

It will fill that array value automaticaly as you type something in INPUT, id will be always at first position in array.

Or you can handle it with object In controller: $scope.data = {};

in HTML <input type="text" ng-model="data.id">