简体   繁体   中英

Send input text to controller's scope in AngularJS

I have this html page:

<div class="rtm-nav">
    <div ng-app>
    <body ng-controller="DemandCtrl" ng-submit="submit()">
        <label>From:
            <input type="text" name="input" ng-model="ctrl.dataa.from">
        </label>
        <label>To:
            <input type="text" name="input" ng-model="ctrl.dataa.to">
        </label>
        <input type="submit" id="submit" value="Apply" />

        <script src="demand/demand.js"></script>
    </body> 
    </div>
</div>

I want to save the input text from the 2 text boxes in the controller's scope. This is how I tried to do it:

class DemandCtrl {
    constructor(ChartDataService) {
        this.ChartDataService = ChartDataService;
        debugger;
        this.dataa = {
            from: ctrl.dataa.from,
            to: ctrl.dataa.to
        };
    }

    $onInit() {
        getData.call(null, this);       
    }

}

I get the error saying:

ReferenceError: ctrl.dataa is not defined

Is any better method to send the data from input text to the controller?

You haven't defined scope which is accepted by your controller. That's why you can't read data from the form. I would also suggest to use <form> to deal with any kind of data submission. So take a look at the refactored example of yours:

==== HTML ======

    <div class="rtm-nav">
        <div ng-app="my-app">
          <form ng-submit="submit()" ng-controller="DemandCtrl">
            <label>From:
                <input type="text" name="input" ng-model="ctrl.data.from">
            </label>
            <label>To:
                <input type="text" name="input" ng-model="ctrl.data.to">
            </label>
            <input type="submit" id="submit" value="Apply" />
          </form>

        </div>
    </div>

===== Controller

    angular.module('my-app', [])
       .controller('DemandCtrl', function($scope) {
            $scope.submit = function() {
                let data = {
                    from: $scope.ctrl.data.from,
                    to: $scope.ctrl.data.to,
                }
               console.log(data);
            };
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM