简体   繁体   English

将输入文本发送到AngularJS中的控制器作用域

[英]Send input text to controller's scope in AngularJS

I have this html page: 我有这个html页面:

<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. 我想从控制器范围的2个文本框中保存输入文本。 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 ReferenceError:ctrl.dataa未定义

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. 我还建议使用<form>处理任何类型的数据提交。 So take a look at the refactored example of yours: 因此,请看一下您的重构示例:

==== HTML ====== ==== 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);
            };
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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