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

前端 未结 2 1594
无人及你
无人及你 2021-01-12 00:47

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) :

 
相关标签:
2条回答
  • 2021-01-12 01:16

    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.

    0 讨论(0)
  • 2021-01-12 01:42

    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">

    0 讨论(0)
提交回复
热议问题